9
label
callback can be used to modify a specific label. So try using any of afterBody
, footer
, afterFooter
callback
https://www.chartjs.org/docs/3.0.2/configuration/tooltip.html#tooltip-callbacks
Example using footer
callback
var branches_canvas = document.getElementById('branches_canvas').getContext('2d');
var branches = new Chart(branches_canvas, {
type: 'bar',
data: {
labels: ['Org1', 'Org2', 'Org3', 'Org4', 'Org5'],
datasets: [{
label: 'Packed',
data: [12, 55, 77, 32, 45],
backgroundColor: [
'#94E3EF',
],
hoverOffset: 4
},
{
label: 'Unpacked',
data: [56, 88, 22, 88, 40],
backgroundColor: [
'#FFA8A8',
],
}
],
},
options: {
plugins: {
tooltip: {
callbacks: {
footer: function(items) {
return 'Total: ' + items.reduce((a, b) => a + b.parsed.y, 0)
}
}
},
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>
<canvas id="branches_canvas"></canvas>
1
You can use the afterBody
callback to show the sum.
Example:
var branches_canvas = document.getElementById('branches_canvas').getContext('2d');
var branches = new Chart(branches_canvas, {
type: 'bar',
data: {
labels: ['Org1','Org2','Org3','Org4','Org5'],
datasets: [
{
label: 'Packed',
data: [12,55,77,32,45],
backgroundColor: [
'#94E3EF',
],
hoverOffset: 4
},
{
label: 'Unpacked',
data: [56,88,22,88,40],
backgroundColor: [
'#FFA8A8',
],
}
],
},
options: {
plugins: {
tooltip: {
callbacks: {
label: function(context) {
var label = context.dataset.label || '';
if (label) {
label += ': ';
}
if (context.parsed.y !== null) {
label += context.parsed.y;
}
return label;
},
afterBody: (ttItem) => (`Sum: ${ttItem.reduce((acc, val) => (acc + val.raw), 0)}`)
}
},
},
scales: {
x: {
stacked: true,
},
y: {
stacked: true
}
},
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.3.2/dist/chart.min.js"></script>
<canvas id="branches_canvas"></canvas>
1
Following tooltip did it for me (with chardata containing your datasets and other information):
tooltip: {
callbacks: {
footer: function(items) {
var total = 0;
for (var i = 0; i < chartData['datasets'].length; i++){
total += chartData['datasets'][i].data[items[0].dataIndex];
}
return 'Total: ' + total
}
}
}
Source:stackexchange.com