Inchara Raveendra
Inchara Raveendra

Reputation: 1667

Plot dynamically added array elements using Highcharts.js

Here is my fiddle : DEMO

The fiddle is a mimic of a real case scenario wherein I get the data from sensors (MQTT)

dataArray[] is populated every 1 second. To show the same I have a button which on click adds an array element to dataArray.

The plotting of graph starts after timeout of 5 seconds. If the button was clicked for 'x' times within 5 seconds of DOM ready, 'x' points will be plotted.

$("#addToArray").click(function() {
  dataArray.push((payload));
  console.log(dataArray);
})

var payload = {
  "temperature": 2,
  "humidity": 80
};

function startGraph() {
   //Graph code
}

If button is pressed after 5 seconds, array element will still be added but not plotted (i.e, any sensor data coming in after 5 seconds will not be plotted)

Is there a way to read the newly added array elements and continue plotting the graph?

Upvotes: 0

Views: 110

Answers (1)

Dmitry
Dmitry

Reputation: 7276

You can use addPoint method of the series to add points dynamically.

$("#addToArray").click(function() {
  //myChartTemperature and myChartHumidity are created  globally in your code
  //so I check if they exist here
  if(myChartTemperature) {
    myChartTemperature.series[0].addPoint(payload.temperature);
  }
  if(myChartHumidity){
    myChartHumidity.series[0].addPoint(payload.humidity);
  }
})

JSFiddle

Upvotes: 3

Related Questions