Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating chart.js bar graph in real time

I am using Chart.js to create a simple bar chart with only two rows and 2 sets of data. I am new to using the library and after reading the examples, I feel comfortable with most of the things there. Here is what I have so far

JS code for graph:

var helpers = Chart.helpers;
var canvas = document.getElementById('bar');


var barChartData = {
    labels: ["IBM", "Microsoft"],
    datasets: [{
      label: "Product A",
      fillColor: "rgba(220,220,220,0.5)",
      strokeColor: "rgba(220,220,220,0.8)",

      data: [25, 75]
    }, {
      label: "Product B",
      fillColor: "rgba(151,187,205,0.5)",
      strokeColor: "rgba(151,187,205,0.8)",

      data: [75, 25]
    }]

  }
  // 
var bar = new Chart(canvas.getContext('2d')).Bar(barChartData, {
  tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>kb",
  animation: false,
})

;

Now, I was wondering if it is possible to update this graph if the data was changed in real time without refreshing the page. For instance if every second the data values keep swapping or something random happens the graph should reflect the changes. I have searched a lot but not found proper document or tutorial explaining this and I would highly appreciate it if someone can show me how to do this.

This is the FIDDLE I have created for work so far.

like image 521
user1010101 Avatar asked Jun 03 '15 03:06

user1010101


1 Answers

You can just use the method addData(), Example:

bar.addData([40, 60], "Google");

Working example - http://jsbin.com/kalilayohu/1/

like image 104
Anand Sudhanaboina Avatar answered Oct 08 '22 23:10

Anand Sudhanaboina