Chartjs-ChartJS v3.X – Limit the string size of label on canvas, without changing tooltip hover string

1👍

After wasting many hours I found a "Tip" highlight on the documentation that should be in the examples, and not just badly highlighted on the "Labeling Axes" page.

When you do a callback for ticks on the chart options settings, you get 3 params to call:

function(value, index, ticks)

I tried in many ways to change the last one because it is the array of all ticks with their labels, and it is the only one where the label string appears so I was trying to modify it.

You’d think at first that the "value" parameter is the one to be changed, but it returns the exactly same integer value as the "index" parameter on each callback iteration, so I thought the only one the I could manipulate to change the string was the "ticks" array, but I was completely wrong.

You actually need to call a special function called getLabelForValue().

The working code ended up like this:

const configTotal = {
    type: 'bar',
    data: dataTotal,
    options: {
        scales: {
            y: {
                beginAtZero: true
            },
            x: {
                ticks: {
                    callback: function(value, index, ticks_array) {
                        let characterLimit = 12;
                        let label = this.getLabelForValue(value);
                        if ( label.length >= characterLimit) {
                            return label.slice(0, label.length).substring(0, characterLimit -1).trim() + '...';
                        }
                        return label;
                    }
                }
            }
        }
    },
};

I hope this helps anyone having the same problem as me.

Maybe all the time I wasted is all on me for not reading every single line with more patience, but in my opinion, this documentation lacks a lot more example codes for accessing properties and callback parameters and it’s object values, the way it is just showing the type of object and returns of each class method call, makes it very confusing for non-experienced on chart.js users.

Leave a comment