Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a second set of labels to a Chart.js doughnut chart?

Tags:

chart.js

I have a doughnut graph created using Chart.js with two datasets. The graph displays the number of employees in offices around the world, with the second dataset breaking this down into permanent and contract employees.

There's a jsfiddle of this running here: https://jsfiddle.net/tetsujin1979/tt3ch8z7/

The "labels" attribute of the options for the graph contains the names of the offices, but since there is only one array of labels, they are repeated for the second dataset, and appear on the mouseover text for it.

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'
      },
      {
        data: [60,64,100,131,71,81,337,276,405,118],
        backgroundColor: [chartColors.purple, chartColors.grey],
        label: 'Permanent/Contract'
      }
    ],
    labels: ['London', 'New York', 'Paris', 'Moscow', 'Mumbai']
  }
};

var ctx = document.getElementById('employees-graph').getContext('2d');
var employeesGraph = new Chart(ctx, config);

Is it possible to specify a second array of labels for the permanent/contract dataset so the hover text displays the values from this second

like image 395
Joseph McCarthy Avatar asked Dec 04 '22 20:12

Joseph McCarthy


1 Answers

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];
      }
    }
  }
}   
like image 159
Aniko Litvanyi Avatar answered Mar 23 '23 01:03

Aniko Litvanyi