Home > database >  How to add percentage in pie chart of chart js without importing plugins scripts
How to add percentage in pie chart of chart js without importing plugins scripts

Time:07-07

I want to show the percentage distribution in pie chart. My current chart is perfect, except it does not have percentage labels. How to add percentage. my code looks like;

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>
<body>

<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = [
  "#b91d47",
  "#00aba9",
  "#2b5797",
  "#e8c3b9",
  "#1e7145"
];

new Chart("myChart", {
  type: "pie",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options: {
    title: {
      display: true,
      text: "World Wide Car Production"
    }
  }
});
</script>

</body>
</html>

CodePudding user response:

You just need to import some <script> from chart js. and then just modify little your code as below;

<!DOCTYPE html>
<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>

<canvas id="myChart" style="width:100%;max-width:600px"></canvas>

<script>
var xValues = ["Italy", "France", "Spain", "USA", "Argentina"];
var yValues = [55, 49, 44, 24, 15];
var barColors = [
  "#b91d47",
  "#00aba9",
  "#2b5797",
  "#e8c3b9",
  "#1e7145"
];
var ctx = document.getElementById("myChart").getContext('2d');
var myChart =new Chart(ctx, {
  type: "pie",
  data: {
    labels: xValues,
    datasets: [{
      backgroundColor: barColors,
      data: yValues
    }]
  },
  options:{
    tooltips: {
      enabled: true
    },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
  
          let sum = ctx.dataset._meta[0].total;
          let percentage = (value * 100 / sum).toFixed(2)   "%";
          return percentage;
  
  
        },
        color: '#fff',
      }
    },
    title: {
        display: true,
        text: "World Wide Car Production"
      }
    }
});
</script>
</body>
</html>

  • Related