如何向 Chart.js 圆环图添加第二组标签?圆环、标签、Chart、js

2023-09-07 12:17:48 作者:往后随风走

我有一个使用 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.

这里有一个 jsfiddle:https://jsfiddle.net/tetsujin1979/tt3ch8z7/

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

推荐答案

向两个数据集添加一个 labels 数组

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