score:2

Accepted answer

edit:

i noticed that if the chart was redrawn (e.g. if the browser window is resized) the legend would lose the extra text.

i've modified the approach to work as an inline plugin so that the label object is modified before the legend is drawn.

let labels = ['a', 'b', 'c', 'd'],
  series = [4, 2, 1, 3],
  mychart = new chart(document.getelementbyid('chart'), {
    type: 'doughnut',
    data: {
      labels: labels,
      datasets: [{
        data: series,
        backgroundcolor: ['red', 'blue', 'green', 'orange']
      }]
    },
    options: {
      maintainaspectratio: false
    },
    plugins: [{
      afterlayout: function(chart) {
        let total = chart.data.datasets[0].data.reduce((a, b) => {
          return a + b;
        });
        chart.legend.legenditems.foreach(
          (label) => {
            let value = chart.data.datasets[0].data[label.index];

            label.text += ' - ' + (value / total * 100).tofixed(0) + '%'
            return label;
          }
        )
      }
    }]
  });
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/2.7.2/chart.min.js"></script>
<canvas id="chart"></canvas>

score:1

chart.js 3.xx

i've included a sample for version 3.5 too. you can alter the legend text by overriding the generatelabels method.

let labels = ['a', 'b', 'c', 'd'],
  series = [4, 2, 1, 3],
  mychart = new chart(document.getelementbyid('chart'), {
    type: 'doughnut',
    data: {
      labels: labels,
      datasets: [{
        data: series,
        backgroundcolor: ['red', 'blue', 'green', 'orange']
      }]
    },
    options: {
      maintainaspectratio: false,
    plugins: {
      legend: {
        display: true,
        position: "bottom",
        align: "center",
        fontfamily: "arial",
        labels: {
          usepointstyle: true,
          fontcolor: "red",
          generatelabels(chart) {
            const data = chart.data;
            if (data.labels.length && data.datasets.length) {
              const {labels: {pointstyle}} = chart.legend.options;
  
              return data.labels.map((label, i) => {
                const meta = chart.getdatasetmeta(0);
                const style = meta.controller.getstyle(i);
                
                return {
                  text: 'this is ' + label + ' - ' + chart.data.datasets[0].data[i],
                  fillstyle: style.backgroundcolor,
                  strokestyle: style.bordercolor,
                  linewidth: style.borderwidth,
                  pointstyle: pointstyle,
                  hidden: !chart.getdatavisibility(i),
  
                  index: i
                };
              });
            }
            return [];
          }
        }
    }
      }
    }
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/chart.js/3.5.1/chart.min.js"></script>
<canvas id="chart"></canvas>


Related Query

More Query from same tag