How to push datasets dynamically for bar chart? - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

How to push datasets dynamically for bar chart?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Chart.js - Add dataset example</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  www . ja v  a  2 s  .c om*/
var ctx = document.getElementById("barChart");
var barChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["Dog", "Cat", "Pangolin"],
        datasets: [{
               backgroundColor: '#00ff00',
            label: '# of Votes 2016',
            data: [12, 19, 3]
            }]
      }
});
function addData(chart, label, color, data) {
      chart.data.datasets.push({
       label: label,
      backgroundColor: color,
      data: data
    });
    chart.update();
}
// inserting the new dataset after 3 seconds
setTimeout(function() {
   addData(barChart, '# of Votes 2017', '#ff0000', [16, 14, 8]);
}, 3000);
    }

      </script> 
   </head> 
   <body> 
      <canvas id="barChart" width="400" height="400"></canvas>  
   </body>
</html>

Related Tutorials