Update a chartjs by javascript function - Javascript Chart.js

Javascript examples for Chart.js:Chart Configuration

Description

Update a chartjs by javascript function

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS Line Chart</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.3.0/Chart.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//w ww  .  j  a va 2 s  . com
var lab = {
     fontSize: 8,
     boxWidth: 20
}
var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderWidth: 1
    }, {
      label: '# of Points',
      data: [7, 11, 5, 8, 3, 7],
      borderWidth: 1
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          reverse: false
        }
      }]
    }
  }
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, options);
var data = {
  labels: ["Done", "In progress", "Not"],
  datasets: [{
    label: '# of Votes',
    data: [4, 15, 3],
    backgroundColor: [
      'rgba(255, 99, 132, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      '#ccf9d6'
    ],
    borderColor: [
      'rgba(255,99,132,1)',
      'rgba(54, 162, 235, 1)',
      'green'
    ],
    borderWidth: 1
  }]
}
function addData(chart, label, data) {
  chart.data.labels.push(label);
  chart.data.datasets.forEach((dataset) => {
    dataset.data.push(data);
  });
  chart.update();
}
setTimeout(function(){
    addData(myChart,lab, data);
}, 2000);
    }

      </script> 
   </head> 
   <body>  
      <canvas id="myChart" class="chartjs hidden-xs" width="300" height="150"></canvas>   
   </body>
</html>

Related Tutorials