Skip to main content

Unable to add a slider in Plotly.js

I tried to add a slider to change the value of scaleFactor which has been added in the code. But even after writing down the steps and arguments I'm unable to add the slider in the existing 'var layout' and thus getting no results.

Here is the code that I've written to implement the slider

var scaleFactor = 120; // adjust this to change the scale of the cones
var velocity_trace_cones = [];

// code for creating velocity cones goes here

var data = [pressure_trace_edges, velocity_trace_nodes, velocity_trace_edges, ...velocity_trace_cones];

var steps = [];
for (var i = 0; i <= 10; i++) {
    var newScaleFactor = i * 10;
    var newData = [];
    for (var j = 0; j < velocity_trace_cones.length; j++) {
        var cone = velocity_trace_cones[j];
        var newCone = Object.assign({}, cone); // create a deep copy of the cone object
        newCone.u = [cone.u[0] * newScaleFactor];
        newCone.v = [cone.v[0] * newScaleFactor];
        newCone.w = [cone.w[0] * newScaleFactor];
        newData.push(newCone);
    }
    var step = {
        label: newScaleFactor.toString(),
        method: 'update',
        args: [{visible: false}, {visible: false}, {visible: false}, ...newData] // replace the velocity cones with new ones based on the new scale factor
    };
    steps.push(step);
}

And here is the part where I tried to implement the slider into an existing layout:

updatemenus: [{
            buttons: [{
                method: 'update',
                args: [{visible: false}, {visible: true}, {visible: true}, ...velocity_trace_cones], // show only the nodes and edges by default
                label: 'Reset'
            }],
            direction: 'left',
            pad: {t: 50, r: 10},
            showactive: false,
            type: 'buttons',
            x: 0.1,
            y: 1.1
        }],
    sliders: [{
        steps: steps,
        active: 0,
        x: 0.1,
        len: 0.9,
        pad: {t: 50, b: 10},
        currentvalue: {
            xanchor: 'right',
            prefix: 'Scale Factor: ',
            font: {size: 20, color: '#888'}
        },
        transition: {duration: 500, easing: 'cubic-in-out'} // add transition to slider
    }],
    xaxis: {title: 'X Axis'},
    yaxis: {title: 'Y Axis'},
    zaxis: {title: 'Z Axis'},

    //for changing the 2D view
    xaxis: {
        visible: false,
        showgrid: false,
    },
    yaxis: {
        visible: false,
        showgrid: false,
    },
    zaxis: {
        visible: false,
        showgrid: false,
    }
};
Plotly.newPlot('network', data, layout);
  
                })

As you can see I tried the same Plotly.newPlot which I guess is returning no results

If you can make any changes it would be a great help.

My full code:

<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>
            Visualization
        </title>
        <link rel="stylesheet" href="style.css">
        <script src="https://cdn.plot.ly/plotly-1.58.5.min.js"></script>
        <style>
            .graph-container {
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
            }
            .main-panel {
                width: 100%;
                height: 800px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
            }
            .side-panel {
            position: fixed;
            top: 0;
            bottom: 0;
            right: -300px;
            width: 300px;
            background-color: #f2f2f2;
            transition: right 0.5s;
            overflow-y: auto;
            padding: 20px;
        }
           
            .side-panel.open {
            right: 0;
            }

            .arrow {
            position: absolute;
            top: 20px;
            left: 20px;
            width: 0;
            height: 0;
            border-top: 20px solid transparent;
            border-bottom: 20px solid transparent;
            border-right: 20px solid #2196F3;
            cursor: pointer;
        }

            .arrow.open {
                transform: rotate(180deg);
            }
        </style>

    </head>
    <body>
        
        <div class="graph-container">
            
            <div id="network" class="main-panel"></div>
            <div id="graph" class="side-panel">
                <div class="arrow"></div>
            </div>
        </div>

        <div id="main">
            <!-- <button class="openbtn" onclick="openNav()">ā˜° Open Sidebar</button>   -->
          </div>

        <script>

            function openNav() {
                document.getElementById("graph").style.width = "500px";
                document.getElementById("main").style.marginLeft = "500px";
            }
            function closeNav() {
                document.getElementById("graph").style.width = "0";
                document.getElementById("main").style.marginLeft= "0";
            }

            const sidepanel = document.querySelector('.side-panel');
            const arrow = document.querySelector('.arrow');

            arrow.addEventListener('click', function() {
            sidepanel.classList.toggle('open');
            arrow.classList.toggle('open');
        });

            //read the data from the json file
            fetch("results.json")
                .then(response => response.json())
                .then( data => {
                    //This part of the code is used to used initialize the variables which will be used to create a network graph

                    //Initializing array for storing the variables
                    var nnodes = data.nnodes;
                    var nedges = data.nedges;
                    var ncones = data.ncones;
                    var x = data.x;
                    var y = data.y;
                    var z = data.z;
                    var edge_x = data.edge_x;
                    var edge_y = data.edge_y;
                    var edge_z = data.edge_z;
                    var pressure_edge_gradient = data.pressure_gradient;

                    console.log(data)
                    // Velocity and the max and min values of the velocity
                    var velocity = data.velocity;
                    var max_velocity = data.max_velocity;
                    var min_velocity = data.min_velocity;

                    //This part of code is used to initialize the variables which will be used to create cones
                    var x_cone = data.x_cone;
                    var y_cone = data.y_cone;
                    var z_cone = data.z_cone;
                    var u_cone = data.u_cone;
                    var v_cone = data.v_cone;
                    var w_cone = data.w_cone;
                    console.log(x_cone[0])

                    //Keeping a list of true and false values for the concentration and the cones which are used while displaying through layout
                    var TrueList_cones = [];
                    var FalseList_cones = [];
                    for (var i = 0; i < ncones; i++) {
                        TrueList_cones.push(true);
                        FalseList_cones.push(false);
                    };

                    //This part of the code is used to create a pressure graph
                    //Creating Edges for pressure graph
                    var pressure_trace_edges = {
                        x: edge_x,
                        y: edge_y,
                        z: edge_z,
                        mode: 'lines',
                        line: {
                            colorscale: "YlOrRd",
                            color: pressure_edge_gradient,
                            width: 5,
                            showscale: true,
                            //decrease the size of the colorbar
                            colorbar: {
                                thickness: 20,
                                len: 0.5,
                                x: 0.9,
                                y: 0.5,
                                title: {
                                    text: "Pressure",
                                    side: "right"
                                }
                            }
                        },
                        type: 'scatter3d',
                        name: "Pressure Edges",
                        hoverinfo: 'none',
                        visible: true,
                        showlegend: true,
                        
                        //set the position of the legend
                    };

                    //This part of the code is used to create a velocity graph
                    //Creating nodes for velocity graph
                    
                    var velocity_trace_nodes = {
                        x: x,
                        y: y,
                        z: z,
                        mode: 'markers',
                        marker: {
                            size: Array(nnodes).fill(6),
                            sizeref: 0.5, 
                            
                            color: "rgb(200,200,200))",
                            showscale: false,
                        },
                        type: 'scatter3d',
                        name: "Velocity Nodes",
                        hoverinfo: 'none',
                        visible: false,
                        showlegend: false,
                    };

                    //Creating edges for velocity graph
                    var velocity_trace_edges = {
                        x: edge_x,
                        y: edge_y,
                        z: edge_z,
                        mode: 'lines',
                        line: {
                            color: "rgb(200,200,200)",
                            width: 5,
                            showscale: true,
                        },
                        type: 'scatter3d',
                        name: "Velocity Edges",
                        hoverinfo: 'none',
                        showlegend: false,
                        visible: false,
                        showscale: false,
                        
                    };

                    //Creating cones for velocity graph
                    var scaleFactor = 120; // adjust this to change the scale of the cones
var velocity_trace_cones = [];

// code for creating velocity cones goes here

var data = [pressure_trace_edges, velocity_trace_nodes, velocity_trace_edges, ...velocity_trace_cones];

var steps = [];
for (var i = 0; i <= 10; i++) {
    var newScaleFactor = i * 10;
    var newData = [];
    for (var j = 0; j < velocity_trace_cones.length; j++) {
        var cone = velocity_trace_cones[j];
        var newCone = Object.assign({}, cone); // create a deep copy of the cone object
        newCone.u = [cone.u[0] * newScaleFactor];
        newCone.v = [cone.v[0] * newScaleFactor];
        newCone.w = [cone.w[0] * newScaleFactor];
        newData.push(newCone);
    }
    var step = {
        label: newScaleFactor.toString(),
        method: 'update',
        args: [{visible: false}, {visible: false}, {visible: false}, ...newData] // replace the velocity cones with new ones based on the new scale factor
    };
    steps.push(step);
}

//creating a list for dummy nodes for concentration nodes
var layout = {
    updatemenus: [
        {
            x: 0,
            y: 15.5,
            yanchor: "top",
            xanchor: "left",
            showactive: false,
            direction: "Right",
            height: 8000,
            width: 8000,
            buttons: [
                {
                    method: "restyle",
                    args: ["visible", [true,false,false,...FalseList_cones]],
                    label: "Pressure"
                },
                {
                    method: "restyle",
                    args: ["visible", [false,true,true,...TrueList_cones]],
                    label: "Velocity"
                },
            ],
        },
    ],

    updatemenus: [{
            buttons: [{
                method: 'update',
                args: [{visible: false}, {visible: true}, {visible: true}, ...velocity_trace_cones], // show only the nodes and edges by default
                label: 'Reset'
            }],
            direction: 'left',
            pad: {t: 50, r: 10},
            showactive: false,
            type: 'buttons',
            x: 0.1,
            y: 1.1
        }],
    sliders: [{
        steps: steps,
        active: 0,
        x: 0.1,
        len: 0.9,
        pad: {t: 50, b: 10},
        currentvalue: {
            xanchor: 'right',
            prefix: 'Scale Factor: ',
            font: {size: 20, color: '#888'}
        },
        transition: {duration: 500, easing: 'cubic-in-out'} // add transition to slider
    }],
    xaxis: {title: 'X Axis'},
    yaxis: {title: 'Y Axis'},
    zaxis: {title: 'Z Axis'},

    //for changing the 2D view
    xaxis: {
        visible: false,
        showgrid: false,
    },
    yaxis: {
        visible: false,
        showgrid: false,
    },
    zaxis: {
        visible: false,
        showgrid: false,
    }
};
Plotly.newPlot('network', data, layout);
  
                })
        </script>

    </body>
</html>
Via Active questions tagged javascript - Stack Overflow https://ift.tt/gBhXkJi

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...