Chartjs-Showing Percentage instead of count inside piechart

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

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.

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.

Leave a comment