0

I am using chart.js & chartjs-plugin-datalabels plugin. Right now graph is showing count while hovering the graph and also inside the graph. But I want to show percentage inside the graph instead of count. How can I do that?

My codepen link - https://codepen.io/kaushik-kowboy/pen/BaGxKwy

<!DOCTYPE html>
<html>
<head>
  <title>Total Chart - Pie Chart with Labels</title>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.0.0"></script>
  <style>
    #totalChart{
        width: 400px !important;
        height: 400px !important;
    }
  </style>
</head>
<body>
  <div style="text-align: center;">
    <h2>Total Chart - Pie Chart with Labels</h2>
    <canvas id="totalChart" width="400" height="400"></canvas>
  </div>

  <script>
        var totalLabels = ["HD","SKY"];
        var totalData = ["138","251"];

        // Generate Facebook pie chart
        var facebookCtx = document.getElementById('totalChart');
        new Chart(facebookCtx, {
            type: 'pie',
            data: {
                labels: totalLabels,
                datasets: [{
                    label: 'no of Leads',
                    data: totalData,
                    borderWidth: 1
                }]
            },
            options: {
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            },
            plugins: [ChartDataLabels],
                options: {
                        
                }
        });
  </script>
</body>
</html>```



I have tried to display the percentage amount using ChartDataLabels. but I don't know how to do that. Right now only count is showing.
Kaushik C
  • 114
  • 9
  • 1
    https://stackoverflow.com/questions/52044013/chartjs-datalabels-show-percentage-value-in-pie-piece – Telexx Jul 18 '23 at 06:37

3 Answers3

0

Wherever u want to add Percentage ,you should write a map function.

instead of totalData use,

totalData.map((ele)=>(ele/totalData.reduce(arrayTotal)*100)
                datasets: [{
                    label: 'no of Leads',
                    data: totalData.map((ele)=>((ele/totalData.reduce(arrayTotal))*100),
                    borderWidth: 1
                }]

I used reducer funtion,since i thought your chart data may be dynamic. u can find the total of ur counts initially also.like write a seperate function which will find total of ur data.

below is the reducer function

function arrayTotal(total, num) {
  return total + num;
}

or u can find array total using a simple for loop which will iterate through and find total.

  • This one is changing the data. I don't want to change the data ("138","251"). I just want to change the label which is showing inside the chart. kindly check my codepen. – Kaushik C Jul 18 '23 at 07:28
0

Finally I found the solution!

I just changed my js code that I will attach it below

// Generate Total pie chart
totalLabelss = ["HD","SKY"];
totalDatas = [138,251];
    
var totaldata = [{
  data: totalDatas,
  backgroundColor: [
    "#4b77a9",
    "#5f255f", 
  ],
  borderColor: "#fff",
  label: ' No of Leads',
}];
var options = {
  tooltips: {
    enabled: false
  },
  plugins: {
    datalabels: {
      formatter: (value, ctx) => {
        const datapoints = ctx.chart.data.datasets[0].data
        const total = datapoints.reduce((total, datapoint) => total + datapoint, 0)
        const percentage = value / total * 100
        return percentage.toFixed(0) + "%";
      },
      color: '#fff',
    }
  }
};
var totalCtxs = document.getElementById("totalChart").getContext('2d');
new Chart(totalCtxs, {
      type: 'pie',
      data: {
      labels: totalLabelss,
        datasets: totaldata
      },
      options: options,
      plugins: [ChartDataLabels],
});

Code pen link with solution - https://codepen.io/kaushik-kowboy/pen/OJaBwZe

Kaushik C
  • 114
  • 9
0

Sometimes we need to convert array data into percentage data to be used in a graphs and aren't we all look for a simplest and shortest solution for that.

How do we convert array numbers into array percentages to be used in graphs? It is fairly simple. We can get it done by using JavaScript's map prototype and Math.max() functions. Here is an example;

        data = [12, 154, 56, 332, 44, 150, 120];
        barH = 100;  
        max = Math.max(...data); 
        data = data.map(a => a == max ? barH : Math.round(barH - (a * barH / max)));
        console.log(data);

Firstly, we set the bar height max percentage which can be be up to 100.

Then, we look for the max value in the array.

Finally, we create the map for conversion.

Script loops through the array and looks for value that matches the max value.

If there is a match, then returns the max bar height for this array value.

If there is no match, then getting the percentage ratio of the array value relative to max value and return it.

Simply, pass your values into data array and read what console.log outputs.

esenkaya
  • 99
  • 4