JavaScript Chart.js - 在工具提示上显示的自定义数据格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28568773/
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:00:39  来源:igfitidea点击:

JavaScript Chart.js - Custom data formatting to display on tooltip

javascriptstring-formattingnumber-formattingcode-formattingchart.js

提问by Laura Thomas

I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!

我在这里查看了各种文档和类似问题,但似乎找不到特定的解决方案。如果我遗漏了任何明显的内容或重复了这个问题,我深表歉意!

As a bit of background info, I have implemented 4 graphs using the Chart.js plugin and passed in the required data using PHP from a database. This is all working correctly and is fine.

作为一些背景信息,我使用 Chart.js 插件实现了 4 个图形,并使用 PHP 从数据库中传入所需的数据。这一切都正常工作并且很好。

My problem is I need to display the data in the tooltips as formatted data aka. as numeric with %. As an example, one of my data from database is -0.17222. I have formatted it as a percentage to display in my table and all is well. However, when setting the data for the chart.js bar graph, the data is obviously missing this formatting and displaying as the -0.17222 which I do not want.

我的问题是我需要将工具提示中的数据显示为格式化数据。作为带有 % 的数字。例如,我来自数据库的数据之一是 -0.17222。我已经将它格式化为一个百分比显示在我的表格中,一切都很好。但是,在为 chart.js 条形图设置数据时,数据显然缺少此格式并显示为我不想要的 -0.17222。

Sorry, I wanted to post a picture, but my reputation is too rubbish!

不好意思,本来想发图的,可惜我的名声太垃圾了!

I grab data from database, then set into my table:

我从数据库中获取数据,然后设置到我的表中:

var kpiRex = new Handsontable(example1, {
    data: getRexData(),

Then I feed this data like so in the chart section:

然后我在图表部分像这样输入这些数据:

data: kpiRex.getDataAtRow(3)

Any help would be great! I've been stuck on this for hours and it's probably something really simple I am overlooking.

任何帮助都会很棒!我已经坚持了几个小时,这可能是我忽略的一些非常简单的事情。

采纳答案by rtome

You want to specify a custom tooltip template in your chart options, like this :

您想在图表选项中指定自定义工具提示模板,如下所示:

 // String - Template string for single tooltips
 tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
 // String - Template string for multiple tooltips
 multiTooltipTemplate: "<%= value + ' %' %>",

This way you can add a '%' sign after your values if that's what you want.

这样你就可以在你的值后添加一个 '%' 符号,如果这是你想要的。

Here's a jsfiddleto illustrate this.

这是一个jsfiddle来说明这一点

Note that tooltipTemplateapplies if you only have one dataset, multiTooltipTemplateapplies if you have several datasets.

需要注意的是tooltipTemplate适用,如果你只有一个数据集,multiTooltipTemplate如果有多个数据集应用。

This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.

文档全局图表配置部分中提到了此选项。看看吧,值得检查一下可以在那里自定义的所有其他选项。

Note that Your datasets should only contain numeric values. (No % signs or other stuff there).

请注意,您的数据集应仅包含数值。(那里没有 % 标志或其他东西)。

回答by Kyrth

For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:

对于 chart.js 2.0+,这已经改变了(不再有 tooltipTemplate/multiTooltipTemplate)。对于那些只想访问当前未格式化的值并开始调整它的人,默认工具提示与以下内容相同:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return tooltipItem.yLabel;
            }
        }
    }
}

I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:

即,您可以将修改返回到tooltipItem.yLabel,它保存 y 轴值。就我而言,我想为财务图表添加美元符号、四舍五入和千位逗号,因此我使用了:

options: {
    tooltips: {
        callbacks: {
            label: function(tooltipItem, data) {
                return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                });
            }
        }
    }
}

回答by Patrice

In chart.js 2.1.6, I did something like this (in typescript):

在chart.js 2.1.6 中,我做了这样的事情(在打字稿中):

  let that = this;
  options = {
    legend: {
      display: false,
      responsive: false
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          let account: Account = that.accounts[tooltipItem.index];
          return account.accountNumber+":"+account.balance+"";
        }
      }
    }
  }

回答by Ariel Cabib

You can give tooltipTemplate a function, and format the tooltip as you wish:

您可以为 tooltipTemplate 提供一个函数,并根据需要格式化工具提示:

tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}

Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.

除了 'value' 属性之外,那些给定的 'v' 参数包含许多信息。您可以在该函数中放置一个“调试器”并自己检查它们。

回答by Admir

tooltips: {
          callbacks: {
            label: (tooltipItem, data) => {
              // data for manipulation
              return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
            },
          },
        },

回答by Shamshad Zaheer

This works perfectly fine with me. It takes label and format the value.

这对我来说非常有效。它需要标签并格式化值。

options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {

                    let label = data.labels[tooltipItem.index];
                    let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
                    return ' ' + label + ': ' + value + ' %';

                }
            }
        }
    }

回答by Alberto De la Rocha

tooltips: {
    callbacks: {
        label: function (tooltipItem) {
            return (new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
            })).format(tooltipItem.value);
        }
    }
}

回答by FranzHuber23

In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback(Thanks to @prokaktus)

在 Chart.Js 2.8.0 中,自定义工具提示的配置可以在这里找到:https: //www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback(感谢@prokaktus

If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWhto the values in the chart), you could do this like:

例如,如果您想显示一些带有前缀或后缀的值(在示例中,脚本kWh向图表中的值添加了一个单位),您可以这样做:

options: {
  rotation: 1 * Math.PI,
  circumference: 1 * Math.PI,
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        console.log(data);
        console.log(tooltipItem);

        var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';

        if (label) {
          label += ' kWh';
        }

        return label;
      }
    }
  }
}

An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/

一个示例小提琴也在这里:https: //jsfiddle.net/y3petw58/1/

回答by Divyanshu Rawat

You need to make use of Label Callback. A common example to round data values, the following example rounds the data to two decimal places.

您需要使用Label Callback。一个常见的数据值四舍五入示例,以下示例将数据四舍五入到两位小数。

var chart = new Chart(ctx, {
    type: 'line',
    data: data,
    options: {
        tooltips: {
            callbacks: {
                label: function(tooltipItem, data) {
                    var label = data.datasets[tooltipItem.datasetIndex].label || '';

                    if (label) {
                        label += ': ';
                    }
                    label += Math.round(tooltipItem.yLabel * 100) / 100;
                    return label;
                }
            }
        }
    }
});

Now let me write the scenario where I used the label callback functionality.

现在让我编写使用标签回调功能的场景。

Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart. In my case it's 4, that's why length of datasets array is 4.

让我们从记录 Label Callback 函数的参数开始,您将在此处看到类似于此数据集的结构,数组由您要在图表中绘制的不同线条组成。在我的例子中它是 4,这就是为什么数据集数组的长度是 4。

enter image description here

在此处输入图片说明

In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.

就我而言,每次我将鼠标悬停在图表中的一条线上时,我都必须对每个数据集执行一些计算,并且必须确定正确的线。

To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.

为了区分不同的行并根据其他行的数据操作悬停工具提示的数据,我必须编写此逻辑。

  callbacks: {
    label: function (tooltipItem, data) {
      console.log('data', data);
      console.log('tooltipItem', tooltipItem);
      let updatedToolTip: number;
      if (tooltipItem.datasetIndex == 0) {
        updatedToolTip = tooltipItem.yLabel;
      }
      if (tooltipItem.datasetIndex == 1) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 2) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
      }
      if (tooltipItem.datasetIndex == 3) {
        updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
      }
      return updatedToolTip;
    }
  } 

Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.

上面提到的场景会派上用场,当您必须在折线图中绘制不同的线条并根据图表中同一索引处属于不同线条的其他点的数据来操作线条悬停点的工具提示时。

回答by Brendan Sluke

This is what my final options section looks like for chart.js version 2.8.0.

这是我在 chart.js 版本 2.8.0 中的最终选项部分的样子。

        options: {
        legend: {
            display: false //Have this or else legend will display as undefined
        },
        scales: {
            //This will show money for y-axis labels with format of $xx.xx
            yAxes: [{
              ticks: {
                beginAtZero: true,
                callback: function(value) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(value);
                }
              }
            }]
        },
        //This will show money in tooltip with format of $xx.xx
        tooltips: {
            callbacks: {
                label: function (tooltipItem) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(tooltipItem.value);
                }
            }
        }
    }

I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)

我想同时显示 y 轴的货币值和将鼠标悬停在它们上方时显示的工具提示值。这适用于显示 49.99 美元和零美分的价值(例如:50.00 美元)