如何向 Chart.js 圆环图添加第二组标签? [英] How to add a second set of labels to a Chart.js doughnut chart?

查看:12
本文介绍了如何向 Chart.js 圆环图添加第二组标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 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];
      }
    }
  }
}   

这篇关于如何向 Chart.js 圆环图添加第二组标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆