ChartJS: datalabels: show percentage value in Pie piece

后端 未结 4 1438
一向
一向 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:32

    I like to add a little in accepted answer, ctx.chart.data.datasets[0].data always gives you entire data even if you filter out some data by clicking on legend, means you will always get same percentage for a country even if you filter out some countries.

    I have used context.dataset._meta[0].total to get the filtered total.

    Here is the working snippet:

    var data = [{
      data: [50, 55, 60, 33],
      backgroundColor: [
        "#4b77a9",
        "#5f255f",
        "#d21243",
        "#B27200"
      ],
      borderColor: "#fff"
    }];
    
    var 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',
        }
      }
    };
    
    
    var ctx = document.getElementById("pie-chart").getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'pie',
      data: {
      labels: ['India', 'China', 'US', 'Canada'],
        datasets: data
      },
      options: options
    });
    
    
    
    

提交回复
热议问题