Chart js to Update line chart having two data sets - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart js to Update line chart having two data sets

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script> 
   </head> 
   <body> 
      <button onclick="clearAndAddNewDataSets()">Add two datasets</button> 
      <canvas id="myChart" width="400" height="400"></canvas> 
      <script type="text/javascript">
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {//  w ww .j  a va2  s  .c o m
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      backgroundColor: 'rgba(255, 99, 132, 0.2)',
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
function clearAndAddNewDataSets() {
  myChart.config.data.datasets = [];
  myChart.config.data.labels = [];
  var labels = ['Label1', 'Label2', 'Label3', 'Label4', 'SQL', 'Label6', 'Label8', 'Label8'];
  var data = [
    [234, 234, 5, 23, 34, 234, 234, 234],
    [22, 1, 123, 14, 2]
  ]
  var colors = ['Red', 'Green'];
  myChart.config.data.labels = labels;
  for (i = 0; i < data.length; i++) {
         var dataSet = {
       label: 'testLabel' + i,
      data: data[i],
      backgroundColor: colors[i]
    }
    myChart.config.data.datasets.push(dataSet);
  }
  myChart.update();
}

      </script>  
   </body>
</html>

Related Tutorials