ChartJS add tooltip to a grouped bar chart
This can be achieved using the following tooltips label callback function :
tooltips: {
mode: 'label',
callbacks: {
label: function(t, d) {
var dstLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel;
return dstLabel + ': ' + yLabel + ' €';
}
}
}
FYI: This has nothing to do with scales
. It would work perfectly fine along with scales
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'DST1',
backgroundColor: '#3e95cd',
data: [3, 2, 4, 5, 1]
}, {
label: 'DST2',
backgroundColor: '#8e5ea2',
data: [2, 4, 1, 2, 5]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
},
title: {
display: true,
text: 'Title'
},
tooltips: {
mode: 'label',
callbacks: {
label: function(t, d) {
var dstLabel = d.datasets[t.datasetIndex].label;
var yLabel = t.yLabel;
return dstLabel + ': ' + yLabel + ' €';
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.js"></script>
<canvas id="ctx"></canvas>
A bit late to the party, but I have recently discovered JavaScript's built-in formatter for currencies, that saves you having to play about with strings and could be helpful here, and is reusable elsewhere in your code!:
const gbp = new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2
});
Being English I have of course done it in GBP, but I found that changing the en-GB
to de-DE
and the 'GBP'
to 'EUR'
worked absolutely fine. Even formatting the decimal points and thousand separators correctly.
EDIT: including how to actually give the formatter a number to format would be useful wouldn't it!
gbp.format(10000); // Returns £10,000.00