【发布时间】:2021-12-10 09:28:12
【问题描述】:
我正在尝试在 ChartJS 3.2.1 中向饼图添加百分比
我从广泛的搜索参考 ChartJS 版本 1 或 2 中找到的所有答案和代码。
包括This question 和This question 和this question,它们都失败或实际上不会更改任何工具提示显示。
https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0 的引用很多,但这不适用于 ChartJS v3;我已经从这里安装了第 3 版的 ChartJS 数据标签:
https://github.com/chartjs/chartjs-plugin-datalabels/releases/tag/v2.0.0
但使用This answer 仍然不起作用。
我在ChartJS Datalabels Plugin documentation 上看不到如何实现我正在寻找的东西。
我正在寻找要在工具提示悬停或饼图本身上显示的每个饼图的百分比,而不是在标签/图例上。
我在ChartJS Tooltip documentation 上看不到任何关于如何实际编辑工具提示文本内容的信息。
所以,我的代码:
JS:
var dnct1 = document.getElementById('DoeNut1');
var myChart1 = new Chart(dnct1, {
type: 'doughnut',
data: {
labels: ["Scotland and Northern Ireland","North East England","North West","Midlands","East Anglia","South England"],
datasets: [{
label: ["Scotland and Northern Ireland","North East England","North West","Midlands","East Anglia","South England"],
data: ["510","887","720","837","993","774","977"],
borderWidth: 0,
hoverOffset: 5,
backgroundColor: ['#F3AC16','#9F9F9F','#FF3355', '#55EE22','#354D73','#553FCF'],
cutout: 0
}]
},
options: {
tooltips: {
enabled: true,
},
layout: {
padding: {
bottom: 25
}
},
plugins: {
/** Imported from a question linked above.
Apparently Works for ChartJS V2 **/
datalabels: {
formatter: (value, dnct1) => {
let sum = 0;
let dataArr = dnct1.chart.data.datasets[0].data;
dataArr.map(data => {
sum += data;
});
let percentage = (value*100 / sum).toFixed(2)+'%';
return percentage;
},
color: '#ff3'
}
}
}
});
HTML:
<div class='chartBox'>
<h2>Title</h2>
<canvas id='DoeNut1'></canvas>
</div>
返回上述无浏览器控制台错误,所有图表均正确显示,但工具提示未显示任何百分比。我看不出有什么问题。
【问题讨论】:
-
@LeeLenalee 我怀疑可能是这种情况,但没有其他变化。不用担心
:-)