javascriptplotlyplotly.jsreal-time-data

Plotly Gauge Dynamic


I have a problem with Plotly JS Gauge that I cannot solve and I have tried a thousand ways to solve it.

How can I use Plotly JS Gauge on real time, dynamically?

I have tried this but it does not work... ;-( :

<script>
    function rand() {
        return Math.floor(Math.random() * (250 - 0) ) + 0;
    }


    var data = [
                {
                    domain: { x: [0, 1], y: [0, 1] },
                    value: 0,
                    title: { text: "Speed" },
                    type: "indicator",
                    mode: "gauge+number"
                }
            ];

    var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
    Plotly.newPlot('myDiv', data, layout);

    var cnt = 0;
    var interval = setInterval(function() {
        Plotly.extendTraces('myDiv', {value: [[rand()]]}, [0])
        if(++cnt === 100) clearInterval(interval);
    }, 300);
</script>

Solution

  • Try using Plotly.update():

    function rand() {
    return Math.floor(Math.random() * (250 - 0) ) + 0;
    }
    
    var data = [
            {
                domain: { x: [0, 1], y: [0, 1] },
                value: 0,
                title: { text: "Speed" },
                type: "indicator",
                mode: "gauge+number"
            }
        ];
    
    var layout = { width: 600, height: 500, margin: { t: 0, b: 0 } };
    Plotly.newPlot('myDiv', data, layout);
    
    var cnt = 0;
    var interval = setInterval(function() {
    Plotly.update('myDiv', {value: rand()}, {}, [0])
    if(++cnt === 100) clearInterval(interval);
    }, 800);
    <head>
    	<!-- Load plotly.js into the DOM -->
    	<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
    </head>
    
    <body>
    	<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
    </body>