I have a Chartjs
stacked bar chart where I want to have the data label aligned to the left, and elapsed (...) if the text is too long.
My chart is set up as follows.
this.chartData = {
labels: ['here is some very long text. even longer xxxxxxx'],
datasets: [
{
label: 'set1',
data: [],
backgroundColor: 'red',
},
{
label: 'set2,
data: [],
backgroundColor: 'green'
},
],
};
this.chart = new Chart(canvasRef.nativeElement, {
type: 'bar',
data: this.chartData,
options: {
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
}
},
responsive: true,
scales: {
x: {
stacked: true,
},
y: {
stacked: true,
beginAtZero: true,
min: 0,
max: 100,
ticks: {
callback: (value) => value + '%'
}
}
}
}
});
When I load this I get the following....
So it has actually pushed the chart (which I want narrow) out of view.
What I would like if to have it as far left as possible, and then ellipse if it is too long, e.g. something like
Is there a way to do this?
Update your scales
object like below. Add ticks
object with characterLimit
value. For now I used it as 5 characters but you can change it to suitable value.
scales: {
x: {
stacked: true,
ticks: {
callback: function(value, index, ticks_array) {
// Maximum character limit
let characterLimit = 5;
// For a category axis, the value is the index so the lookup via getLabelForValue is needed
let label = this.getLabelForValue(value);
// If label length is more than expected then trim it & append ellipsis (...)
if (label.length >= characterLimit) {
return label.slice(0, label.length).substring(0, characterLimit - 1).trim() + '...';
}
// return updated label value.
return label;
}
}
}
}
Documentation