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

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

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!

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

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.

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

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.

对不起,我想发图片,但我的名声太垃圾了!

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.

推荐答案

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

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.

这里有 一个 jsfiddle 来说明这一点.

Here's a jsfiddle to illustrate this.

请注意,tooltipTemplate 适用于您只有一个数据集,multiTooltipTemplate 适用于您有多个数据集.

Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.

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

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).

相关文章