2016-07-25 7 views
1
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script> 
    <body> 
    <div id="myDiv2" style="width: 600px; height: 650px;"><!-- Plotly chart will be drawn inside this DIV --></div> 
    </body> 
    <script> 
    var socket = io(); 
    socket.on('temp', function(temp){ 
     $('#messages').html(temp); 
     var layout = { 
    title: "Live Data Streaming", 
    xaxis: { 
     title: "X Axis", 
     titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
     } 
    }, 
    yaxis: { 
     title: "Live Data", 
     titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
     } 
    } 
    }; 
    var i=0; 
    var loop = setInterval(function() { 
    var trace1 = { 
    x: [i], 
     y: [temp], 
     type: 'line' 
     }; 
     i++; 
    }, 5000); 

     var data = [trace1]; 
     Plotly.newPlot('myDiv2', data, layout); 
    }); 
      </script> 

Der Sockel lauscht auf die Variable temp. Ich möchte diese Temperaturvariable alle fünf Sekunden live in ein Diagramm streamen. Im Moment benutze ich plotly und setze alle fünf Sekunden ein Intervall, aber die Graphen werden nicht in meinem HTML angezeigt. Wenn ich das setInterval entferne, wird das Diagramm gut angezeigt, aber das alte temp wird durch das neue temp ersetzt, anstatt das Diagramm fortzusetzen. Irgendwelche Ideen, wie man diese Daten in Java Script live streamen kann.Live-Streaming mit plotly in Javascript

Antwort

1
var plotDiv = document.getElementById('myDiv2'); 
layout = { 
    hovermode:'closest', 
    title: "Live Data Streaming", 
    xaxis: { 
    title: "X Axis", 
    autorange:true, 
    titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
    } 
    }, 
    yaxis: { 
    title: "Live Data", 
    autorange:true, 
    titlefont: { 
     family: "Verdana, Sans-serif", 
     size: 18, 
     color: "#7f7f7f" 
    } 
    } 
}; 
var data = [{ 
    x: [0], 
    y: [0] 
}]; 

Plotly.plot(plotDiv, data, layout); 

var i = 1; 
setInterval(function(){ 
    socket.once('temp', function(temp){ 
    var update = {x: [[i]],y: [[temp]]}; 
    i++; 
    Plotly.extendTraces(plotDiv, update, [0], 100); 
    }); 

    $('#stop').click(function() { 
    clearInterval(loop); 
    }); 
    }, 5000); 

    plotDiv.on('plotly_click', function(data){ 
    var pts = ''; 
    for(var i=0; i < data.points.length; i++){ 
     pts = 'x = '+data.points[i].x +'\ny = '+ 
     data.points[i].y.toPrecision(4) + '\n\n'; 
    } 
    alert('Data point clicked is located at:\n\n'+pts); 
    }); 

Dies sollte Live-Stream die Daten in perfekt mit Javascript.