How to truncate labels in Chartjs
In this video we will explore how to add truncated labels in Chart js while keeping the full label intact in the tooltip.
In Chart js once the labels are getting to long it will impact the chart. This affects the size of the chart as well and quite often it does not show the chart nicely.
Truncating the label itself can create an issue if it would impact the tooltip as well. This video will show you how to only truncate the label without damaging the tooltip.
Chart JS truncated labels
With the callback we are basically getting the data but modify it before it would display on the labels.
Why Chart js labels impact the size of the chart?
In Chart js the labels are getting a pre-calculated about of space. As the canvas is restricted due to the maintainAspectRatio settings in Chart js. This means it keeps the canvas width and height ratio consistent. This restricts the growth of the chart where it is needed.
The maintainAspectRatio keeps the Chart from adjusting the size if the canvas is nested in a div element that has a pre-determined size. This means the div is leading for the size of the canvas.
This means everything else must fit within the frame. This results in a flexible chartArea which can shrink to make all the other parts fit.
If you look carefully the chartArea is not the canvas but the drawing of the chart only. The legend and the x-axis and y-axis is part of the canvas but is not considered the chartArea.
This means the maintainAspectRatio can only adjust the chartArea. This restricts the shape and impacts everything else. If the canvas does not need to maintain the aspect ratio in that case we can modify this without damaging the chart. To get deeper insight on this watch this video.
How to Resize the Chart and Maintain Aspect Ratio with the ‘maintainAspectRatio’ setting.
The video shows you how to solve a common issue with chart resizing. However, the chartArea is the one that eventually gets impacted. The video will show what is being impacted and how to play around with the maintainAspectRatio.