Check Out the Chart.js Course: Chart.js, The Missing Manual Course

How to truncate labels in Chartjs while keeping the full label value in the tooltips Chart.JS

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

Chart JS truncated labels

In Javascript the truncate method can be used to reduce the label size to the exact amount of characters. However, we will need to work with a callback to adjust specifically a the scales only. This avoids the tooltip being truncated as well.

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.

Chart.js Maintain Aspect Ratio

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.

Was this page helpful?

Leave a comment

Your email address will not be published.