Create pie chart in chartjs - Javascript Chart.js

Javascript examples for Chart.js:Pie Chart

Description

Create pie chart in chartjs

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.2/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//from w ww.ja v  a2 s.  co m
var chartPie = null;
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
function createChartPie(listVoucher, listCount) {
  console.log("creating my chart pie");
  var ctx = document.getElementById("myChartPie").getContext('2d');
  chartPie = new Chart(ctx, {
    type: 'pie',
    data: {
      labels: listVoucher,
      datasets: [{
        label: "Repartition of Warnings",
          backgroundColor: ["rgb(40, 37, 89)", "rgb(54, 162, 235)", "rgb(75, 192, 192)", "rgb(8, 197, 94)", "rgb(255, 99, 132)"],
        data: listCount
      }],
    },
    options: {
      title: {
        display: true,
        text: 'Repartition of Warnings'
      },
      animation: {
         duration : 1000
      }
    }
  });
}
function removeData(chart) {
  while (chart.data.labels.length != 0) {
    chart.data.labels.pop();
    chart.data.datasets.forEach((dataset) => {
      dataset.data.pop();
    });
  }
  chart.update();
}
function addData(chart, label, data) {
  for (var i = 0; i < label.length; i++) {
    chart.data.labels.push(label[i]);
    chart.data.datasets.forEach((dataset) => {
      dataset.data.push(data[i]);
    });
  }
  chart.update();
}
function testUpdate1() {
  removeData(chartPie);
  addData(chartPie, ['aaa', 'bbb', 'ccc', 'ddd', 'eee'], [1, 2, 3, 4, 5]);
}
function testUpdate2() {
  removeData(chartPie);
  addData(chartPie, ['xxx', 'yyy', 'fff', 'bbb', 'nnn'], [5, 4, 3, 2, 1]);
}
createChartPie(['aa', 'bb', 'cc'], [1, 2, 3]);
document.getElementById('chartDataButton').addEventListener('click', testUpdate1);
document.getElementById('chartDataButton2').addEventListener('click', testUpdate2);
    }

      </script> 
   </head> 
   <body>  
      <div class="container chart"> 
         <canvas id="myChartPie"></canvas> 
      </div> 
      <button id="chartDataButton">Change</button> 
      <button id="chartDataButton2">Change2</button>   
   </body>
</html>

Related Tutorials