Reputation: 4292
My example currently looks like this:
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'
}
}
});
Now I want to display the sum of the values from data: [12, 19, 3, 5, 2, 3]
as title of the chart (So, in this case the title would be 44). Some example fiddle is here: https://jsfiddle.net/ktq8mb0z/. How can I achieve that in Chart.Js?
Upvotes: 1
Views: 2142
Reputation: 441
Since ChartJS version 3.x.x:
Therefore, use this configuration:
options: {
rotation: -90,
circumference: 180,
plugins: {
title: {
display: true,
text: 'Total: ' + data.reduce((total, dataPoint) => total + dataPoint, 0),
position: 'bottom',
},
},
}
Upvotes: 1
Reputation: 2138
You can user reduce function
dataset[0].data.reduce((x,y)=>x+y)
or You can also use this
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/[email protected]"></script>
<canvas id="myChart" width="400" height="400"></canvas>
Upvotes: 2