如何在Chart.js甜甜圈图中添加第二组标签? [英] How to add a second set of labels to a Chart.js doughnut chart?

查看:53
本文介绍了如何在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:< a href = https://jsfiddle.net/tetsujin1979/tt3ch8z7/ rel = nofollow noreferrer> 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天全站免登陆