Chartjs-Chart.js + React: How to create a custom label with amount and percentage

0👍

You should use generatedlabels options.

Here is the legend config to use:

  plugins: {
    legend: {
      position: 'right',
      rtl : true,
      labels: {
        usePointStyle: true,
        pointStyle: 'circle',
        generateLabels(chart) {
          const dataset = chart.data.datasets[0];
          const meta = chart.getDatasetMeta(0);
          const total = meta.total;
          const legendItems = Chart.controllers.doughnut.overrides.plugins.legend.labels.generateLabels(chart);
          for (const item of legendItems) {
            const value = dataset.data[item.index];
            const percentage = value / total * 100
            item.text = item.text + ': ' + value + ' / ' + percentage.toFixed(0) + '%';
          }
          return legendItems;
        }
      }
    },
  },

Leave a comment