Cutting off / Adding ellipsis for long labels
Expected behavior
As example, I have bar chart with some long labels on horizontal line. The main problem is that the chart and other labels can be hidden by this reason.
I tried to find the attribute that would helped me to dynamically calculate cutting off or adding ellipsis for these labels, but I can't.
Current behavior
First long label contains all canvas space. I can't see the chart and other labels for this reason.
Reproducible sample
https://codepen.io/corocoto/pen/abYdJBG
Optional extra steps/info to reproduce
No response
Possible solution
I propose to add attribute for these labels, that allows to dynamically calculate cutting off or adding ellipsis.
Context
My project has the separate page for widgets. I can add it by drag-and-drop approach, and easily changing it size on edit mode.
If one of the widgets will be small, but labels'll large - the problem can be reproduce.
chart.js version
latest
Browser name and version
No response
Link to your project
No response
@corocoto as workaround, you could use the axis callbacks, checking the length of the string and cut it (adding ellipsis) if longer then expected. It's not perfect and you must pay attention about new length of the label.
options: {
scales: {
x: {
beforeUpdate(axis) {
const labels = axis.chart.data.labels;
for (let i=0; i<labels.length; i++) {
const lbl = labels[i];
if (typeof lbl === 'string' && lbl.length > 10) {
labels[i] = lbl.substring(0, 10); // cutting
}
}
}
}
}
}
Codepen: https://codepen.io/stockinail/pen/BarjRKZ
@stockiNail, thanks a lot for this tip. It's really great advice. I'm experimenting with beforeUpdate function a little bit later.
P.S. Anyway, it'll be great if the feature with dynamically cutting (adding ellipsis) for long label would be as an attribute or something like this in the next versions. And I wouldn't like to close the issue for this reason.
@stockiNail Is there a way to set a tooltip on the labels with trimming?
@isaac-wahba AFAIK no, at least not out of the box. To do that, you should code a specific plugin (custom one). A good starting point is the answer of @LeeLenaleee in SO: https://stackoverflow.com/questions/71615569/how-to-detect-click-on-chart-js-3-7-1-axis-label, to catch when the cursor is hovering the X axis values.
Thank you, dear @stockiNail
This also works and keeps the tooltip label intact:
options: {
scales: {
y: {
ticks: {
callback: function (value) {
// truncate the labels only in this axis
const lbl = this.getLabelForValue(value as number);
if (typeof lbl === 'string' && lbl.length > 10) {
return `${lbl.substring(0, 10)}...`;
}
return lbl;
},
},
},
}
}
Thank you @engdlee ! That's what I was looking for.