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

六月ゝ 毕业季﹏ 提交于 2019-12-24 00:36:54

问题


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


回答1:


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];
      }
    }
  }
}   


来源:https://stackoverflow.com/questions/50043412/how-to-add-a-second-set-of-labels-to-a-chart-js-doughnut-chart

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!