gpt4 book ai didi

charts - chartjs 向饼图图例添加百分比

转载 作者:行者123 更新时间:2023-12-04 10:46:30 24 4
gpt4 key购买 nike

将百分比值添加到图例标签的最简单方法是什么?

我相信它会使用 generateLabels: function (chart) {},谁能提供一个干净的例子?

最佳答案

似乎没有任何本地方式来显示百分比,但计算它们并将它们设置为标签非常简单:

const data = [1, 2, 3],
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
total = data.reduce((accumulator, currentValue) => accumulator + currentValue),
// ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
labels = data.map(value => Math.round((value / total) * 100) + '%');

new Chart(document.getElementById('chart'), {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: data
}]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart" height="75"></canvas>


(注意:使用 Math.round() 可能会导致某些数字集相加时不等于 100%。)

关于charts - chartjs 向饼图图例添加百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681505/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com