I am trying to update the chart with plotly.js with data from a server. My function should plot updated data in the charts every time new data is sent.
I have two different graphs in my chart. Both with the same X value but different values for the Y axis. I can create the expected graphs in the chart with the first values. But when new values are sent, the restyle function did not update the values.
I don't know how to parse the data to the restyle function. Or, do I need to use a different function?
var source = new EventSource("http://old.iolab.sk/evaluation/sse/sse.php");
source.onmessage = function(event) {
count++;
if(count == 1){ // only on first data from server
var layout = {title: "Website graph"};
var trace1 = {
x: [event.data.match(/\d+/g)[0]],
y: [(event.data.match(/\d+/g)[2] + "." + event.data.match(/\d+/g)[3])], // y1 from server
name: "hehe",
type: 'scatter'
};
var trace2 = {
x: [event.data.match(/\d+/g)[0]],
y: [(event.data.match(/\d+/g)[5] + "." + event.data.match(/\d+/g)[6])], // y2 from server
name: "hehe",
type: 'scatter'
};
Plotly.newPlot("websiteGraph", [trace1, trace2], layout);
return;
}
if(!isClicked){ // keeps updating the chart with data from the server until the button is clicked
trace1 = {'x': [[event.data.match(/\d+/g)[0]]], 'y': [[(event.data.match(/\d+/g)[2] + "." + event.data.match(/\d+/g)[3])]]},
trace2 = {'x': [[event.data.match(/\d+/g)[0]]], 'y': [[(event.data.match(/\d+/g)[5] + "." + event.data.match(/\d+/g)[6])]]};
Plotly.restyle("websiteGraph", trace1+trace2);
}
return;
}
This is the data from the server, one ID is for one update:
id: 0
data: {
data: "x": "0",
data: "y1": "0.05",
data: "y2": "1.03"
data: }
id: 1
data: {
data: "x": "1",
data: "y1": "0.077452406437284",
data: "y2": "1.0998476951564"
data: }
id: 2
data: {
data: "x": "2",
data: "y1": "0.1048994967025",
data: "y2": "1.0893908270191"
data: }
id: 3
data: {
data: "x": "3",
data: "y1": "0.13233595624294",
data: "y2": "1.0086295347546"
data: }
To answer your question, try using Plotly.react or Plotly.newPlot for new data.
Plotly.restyle seems to be wrong (layout changes only?), as well as some argument passed into the functions.
The comments and examples below are from the Plotly docs at https://plotly.com/javascript/plotlyjs-function-reference/#plotlyrestyle.
To see the code in action, check out this fiddle: https://jsfiddle.net/a0cj6bnm/
Note: To me, it seems that restyle is for layout changes only. Not sure though. Instead of 0, restyle can get an array of values but this had no effect on my tests.
The function seems to expect an array and a layout hash as an argument.