如何自定义Chart.js 2.0甜甜圈图的工具提示? [英] How to customize the tooltip of a Chart.js 2.0 Doughnut Chart?
问题描述
我正在尝试使用Chart.js2中的甜甜圈图显示一些数据.
I'm trying to show some data using a doughnut chart from Chart.js2.
我当前的图表如下:
My current chart looks like this:
我想要的输出必须显示另一个属性,即百分比,如下所示:
My desired output must show another attribute, which is the percentage, and looks like this:
我已经阅读了文档,但是由于它非常笼统并且是JavaScript的新手,所以我无法解决.
I've read the documentation, but I can't cope with this because it's very general and I'm new to 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'
]
}]
};
推荐答案
您可以使用图表选项工具提示配置部分自定义工具提示,如下所述:
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
如下面的示例代码所示,您可以更改颜色,大小和样式等内容.查看上面链接的文档以获取可配置选项的完整列表.
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.
在下面的示例中,我将"title"设置为显示标签名称,将"label"设置为显示值,并将百分比添加到"afterLabel".
In the below example, I set the "title" to show the label name, "label" to show the value, and added the percentage to "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
}
}
});
正在工作的JSFiddle: https://jsfiddle.net/m7s43hrs/
Working JSFiddle: https://jsfiddle.net/m7s43hrs/
这篇关于如何自定义Chart.js 2.0甜甜圈图的工具提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!