I am using chart.js v2 in my Angular project to render a bar chart and trying to display the tooltip in the following format (desired output) on each bar. Example: Others: $ 34.5 (ex GST). I have tried labelBefor and LabelAfter callbacks but problem still persists.
Actual Output is attached in the image below!
Code:
loadChart() {
if (Array.isArray(this.monthData)) {
for (let i = 0; i < this.monthData.length; i ) {
this.CCA_DollarClr.push('#BD4FBD');
this.APT_DollarClr.push('#4F77BD');
this.CW_DollarClr.push('lightgrey');
this.SPRA_DollarClr.push('red');
this.OTHER_DollarClr.push('lightgreen');
}
}
if (this.BarChart) {
this.BarChart.destroy();
}
// Bar chart:
this.BarChart = new Chart('barChart', {
type: 'bar',
data: {
labels: this.monthData,
datasets: [{
label: 'CCA',
data: this.CCA_Dollar,
backgroundColor: this.CCA_DollarClr,
borderColor: ['#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD', '#BD4FBD'],
borderWidth: 1
},
{
label: 'APT',
data: this.APT_Dollar,
backgroundColor: this.APT_DollarClr,
borderColor: ['#4F77BD', '#4F77BD', '#4F77BD'],
borderWidth: 1
},
{
label: 'CW',
data: this.CW_Dollar,
backgroundColor: this.CW_DollarClr,
borderColor: ['lightgrey', 'lightgrey', 'lightgrey'],
borderWidth: 1
},
{
label: 'SPRA',
data: this.SPRA_Dollar,
backgroundColor: this.SPRA_DollarClr,
borderColor: ['#4F77BD', '#4F77BD', '#4F77BD'],
borderWidth: 1
},
{
label: 'OTHER',
data: this.OTHER_Dollar,
backgroundColor: this.OTHER_DollarClr,
borderColor: ['lightgrey', 'lightgrey', 'lightgrey'],
borderWidth: 1
}
],
},
options: {
title: {
// text: "Product Usage",
display: true
},
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
},
legend: {
onHover: function (e) {
e.target['style'].cursor = 'pointer';
}
},
hover: {
onHover: function (e) {
var point = this.getElementAtEvent(e);
if (point.length) e.target['style'].cursor = 'pointer';
else e.target['style'].cursor = 'default';
}
},
tooltips: {
// mode: 'index',
// callbacks: {
// afterLabel: function() {
// return ' $ (ex GST)';
// }
// }
}
}
});
}
Is there a way to format the tooltip so that i can put characters in between, at the start and at the end? If i use beforLable it outputs as $ (ext GST) Others: 3.45 which is not the solution. Any guidance will be very much apricated
CodePudding user response:
You will need to use the normal label callback.
Method should look something like this (on mobile so can't test it out so doing this from the top of my head):
callbacks: {
label: (ttItem, data) => {
return `${data.datasets[ttItem.datasetIndex].label}: £${ttItem.yLabel}`
}
}
CodePudding user response:
callbacks: {
label: (item, data) => {
return `${data.datasets[item.datasetIndex].label}: $ ${item.value} (YourText)`;
}
I think you need this please have a try.