[Chartjs]-How to fix bars in Chart.js with long labels

19👍

You were using ChartJs version 2.1.3 in your JSFiddle, which does not seem to handle multiline labels

You can use multilines labels with the following solutions:

var dates = [["Some l-o-o-o-o-", "o-o-o-o-o-o-o-", "n-n-n-n-n-n-g-g-g-", "g-g-g-g label"], "DDD", ["EEE", "FFF", "GGG"], "HHH", "III"];

You can replace a label by an array, and each element of the array will be considered as a new line (See JSFiddle): https://jsfiddle.net/cyuwxh3q/


If your labels are generated dinamically, you can split them with a plugin in your chart configuration :

type: 'bar',
data: {...},
options: {...},
plugins: [{
    beforeInit: function (chart) {
        chart.data.labels.forEach(function (value, index, array) {
            var a = [];
            a.push(value.slice(0, 5));
            var i = 1;
            while(value.length > (i * 5)){
                a.push(value.slice(i * 5, (i + 1) * 5));
                i++;
            }
            array[index] = a;
        })
    }
}]

This function will turn each label into an array of element which length is less or equal to the given value (here 5) (See JSFiddle) : https://jsfiddle.net/jhr5nm17/


Those are two easy ways to handle long labels by replacing them by multiline labels, hope it helps.

Leave a comment