ChartJS: datalabels: show percentage value in Pie piece

后端 未结 4 1439
一向
一向 2020-12-09 02:33

I have a piechart with four labels:

var data = [{
    data: [50, 55, 60, 33],
    labels: [\"India\", \"China\", \"US\", \"Canada\"],
    backgroundColor: [
         


        
4条回答
  •  再見小時候
    2020-12-09 03:25

    You could use the tooltip with an Array reducer to perform the percentage calculation and display it.

      tooltips: {
        callbacks: {
          label: function (tooltipItem, data) {
            try {
              let label = ' ' + data.labels[tooltipItem.index] || '';
    
              if (label) {
                label += ': ';
              }
    
              const sum = data.datasets[0].data.reduce((accumulator, curValue) => {
                return accumulator + curValue;
              });
              const value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
    
              label += Number((value / sum) * 100).toFixed(2) + '%';
              return label;
            } catch (error) {
              console.log(error);
            }
          }
        }
      }
    

提交回复
热议问题