Javascript 如何自定义 Chart.js 2.0 圆环图的工具提示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43604597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:01:39  来源:igfitidea点击:

How to customize the tooltip of a Chart.js 2.0 Doughnut Chart?

javascripttooltipcustomizationchart.js2

提问by user7334203

I'm trying to show some data using a doughnut chart from Chart.js2.

我正在尝试使用 Chart.js2 中的圆环图显示一些数据。

My current chart looks like this:

我当前的图表如下所示:

current chart

当前图表

My desired output must show another attribute, which is the percentage, and looks like this:

我想要的输出必须显示另一个属性,即百分比,如下所示:

desired chart with percentage

所需的百分比图表

I've read the documentation, but I can't cope with this because it's very general and I'm new to JavaScript.

我已经阅读了文档,但我无法解决这个问题,因为它非常通用,而且我是 JavaScript 的新手。

My code for the first chart is the following:

我的第一个图表代码如下:

const renderCashCurrencyPie = (cashAnalysisBalances) => {
  if (cashAnalysisBalances) {
    const currenciesName = cashAnalysisBalances
    .map(curName => curName.currency);

    const availableCash = cashAnalysisBalances
    .map(avCash => avCash.availableCash);

    let currenciesCounter = 0;
    for (let i = 0; i < currenciesName.length; i += 1) {
      if (currenciesName[i] !== currenciesName[i + 1]) {
        currenciesCounter += 1;
      }
    }

    const currenciesData = {
      labels: currenciesName,
      datasets: [{
        data: availableCash,
        backgroundColor: [
          '#129CFF',
          '#0C6DB3',
          '#FF6384',
          '#00FFFF'
        ],
        hoverBackgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
          '#00FFFF'
        ]
      }]
    };

回答by Tot Zam

You can customize the tooltips using the chart options tooltip configuration section, as explained here: http://www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-configuration

您可以使用图表选项工具提示配置部分自定义工具提示,如下所述:http: //www.chartjs.org/docs/latest/configuration/tooltip.html#tooltip-configuration

As shown in the example code below, you can change things like color, sizing and styles. Check out the documentation linked above for a full list of configurable options.

如下面的示例代码所示,您可以更改颜色、大小和样式等内容。查看上面链接的文档以获取可配置选项的完整列表。

If you want to add the percentage to the tooltip display, you can use tooltip callbacks. The documentation has a list of all the possible customizable callback fields.

如果要将百分比添加到工具提示显示中,可以使用工具提示回调。该文档列出了所有可能的可自定义回调字段。

In the below example, I set the "title" to show the label name, "label" to show the value, and added the percentage to "afterLabel".

在下面的示例中,我设置了“title”来显示标签名称,“label”来显示值,并将百分比添加到“afterLabel”中。

var myChart = new Chart(ctx, {
  type: 'doughnut',
  data: data,
  options: {
    tooltips: {
      callbacks: {
        title: function(tooltipItem, data) {
          return data['labels'][tooltipItem[0]['index']];
        },
        label: function(tooltipItem, data) {
          return data['datasets'][0]['data'][tooltipItem['index']];
        },
        afterLabel: function(tooltipItem, data) {
          var dataset = data['datasets'][0];
          var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
          return '(' + percent + '%)';
        }
      },
      backgroundColor: '#FFF',
      titleFontSize: 16,
      titleFontColor: '#0066ff',
      bodyFontColor: '#000',
      bodyFontSize: 14,
      displayColors: false
    }
  }
});

Working JSFiddle: https://jsfiddle.net/m7s43hrs/

工作 JSFiddle:https://jsfiddle.net/m7s43hrs/

回答by Merenzo

As per @Tot Zam's answer, but using arrow functions for brevity:

根据@Tot Zam 的回答,但为了简洁起见,使用箭头函数:

options: {
  tooltips: {
    callbacks: {
      title: (items, data) => data.datasets[items[0].datasetIndex].data[items[0].index].myProperty1,
      label: (item, data) => data.datasets[item.datasetIndex].data[item.index].myProperty2
    }
  }
}