[Chartjs]-How to add a second set of labels to a Chart.js doughnut chart?

17👍

Add a labels array to both of the datasets

var config = {
  type: 'doughnut',
  data: {
    datasets: [
      {
        data: [124,231,152,613,523],
        backgroundColor: [chartColors.red, chartColors.orange, chartColors.yellow, chartColors.green, chartColors.blue],
        label: 'Offices',
        labels: ['London', 'New York', 'Paris', 'Moscow', 'Mumbai']
      },
      {
        data: [60,64,100,131,71,81,337,276,405,118],
        backgroundColor: [chartColors.purple, chartColors.grey],
        label: 'Permanent/Contract',
        labels: ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
      }
    ]
  }
};

And add the following to the options:

options: {
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var dataset = data.datasets[tooltipItem.datasetIndex];
        var index = tooltipItem.index;
        return dataset.labels[index] + ": " + dataset.data[index];
      }
    }
  }
}   

2👍

As I’m writing this, on Chartjs version 4.2.1, Aniko Litvanyi’s callbacks for label function doesn’t work.

They have changed the namespace to options.plugins.tooltip.callbacks

For more info chartjs docs

options:{
   plugins:{
      tooltip: {
           callbacks: {
                label: function(context) {
                var index = context.dataIndex;
                return context.dataset.labels[index] + ': ' + context.dataset.data[index];
            }
         }
      },    
   }
}    

Leave a comment