I am trying to setup a bar chart using the Charts.js v2 library.
The issue i'm running into is i want to format the x axis labels differently to the tooltip labels.
For instance, if i have a label like "Super long label that will be trimmed" along the x axis, with the below code that would shown as "Super long label that...".
Chart.scaleService.updateScaleDefaults('category', {
ticks: {
callback: function(tick) {
var characterLimit = 20;
if ( tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit -1).trim() + '...';;
}
return tick;
}
}
});
Full fiddle: https://jsfiddle.net/kvszjr7g/3/
This works correctly.
But the tooltips that are shown when you hover over the bar are also trimmed. What i would like is for the full text of the label to be shown in the tooltip.
I've tried to use a copy of the string in the above method, that's why i've added tick.slice
. Whatever i've tried up to this point always effects both the x axis labels and tooltip labels.
I'm pretty lost at this point, what would be the best way to approach this?
First, you would better edit your chart properties directly from the options of the chart, and not in the scale service as you did so that it won't affect every chart on your page (if you have several).
To achieve what you already did, add the function you used in your options :
options: {
scales: {
xAxes: [{
ticks: {
callback: function(tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';
}
return tick;
}
}
}]
},
}
It is basically an edit of what is displayed as labels on your xAxe.
To fix it, you'll also need to edit the callback of the tooltip :
options: {
// other options here, `scales` for instance
// ...
tooltips: {
callbacks: {
// We'll edit the `title` string
title: function(tooltipItem){
// `tooltipItem` is an object containing properties such as
// the dataset and the index of the current item
// Here, `this` is the char instance
// The following returns the full string
return this._data.labels[tooltipItem[0].index];
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With