![](/img/trans.png)
[英]How can I add some text in the middle of a half doughnut chart in Chart.JS?
[英]How can I add the sum of all values as chart title for a doughnut chart in Chart.Js?
我的示例目前如下所示:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
title: {
display: true,
text: 'Custom Chart Title',
position: 'bottom'
}
}
});
現在我想顯示data: [12, 19, 3, 5, 2, 3]
值的總和data: [12, 19, 3, 5, 2, 3]
作為圖表的標題(因此,在這種情況下,標題將為 44)。 一些示例小提琴在這里: https : //jsfiddle.net/ktq8mb0z/ 。 我怎樣才能在 Chart.Js 中實現這一點?
您可以用戶減少功能
dataset[0].data.reduce((x,y)=>x+y)
或者您也可以使用它
dataset.reduce((t,d) => t + d.data.reduce((a,b) => a+b),0)
var ctx = document.getElementById("myChart"); var dataset=[{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }]; var myChart = new Chart(ctx, { type: 'doughnut', data: { labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: dataset }, options: { rotation: 1 * Math.PI, circumference: 1 * Math.PI, title: { display: true, text: 'Custom Chart Title and Sum is : '+dataset.reduce((t,d) => t + d.data.reduce((a,b) => a+b),0), position: 'bottom' } } });
.snippet-code .snippet-result .snippet-result-code{ min-height:640px!important; height:640px!important; }
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script> <canvas id="myChart" width="400" height="400"></canvas>
從 ChartJS 3.xx 版開始:
因此,使用此配置:
options: {
rotation: -90,
circumference: 180,
plugins: {
title: {
display: true,
text: 'Total: ' + data.reduce((total, dataPoint) => total + dataPoint, 0),
position: 'bottom',
},
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.