Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS: Limit label's length on an axis and show a tooltip on hover?

Tags:

chart.js

So the issue is having too long and dynamic chart labels. Is there a way to set a limit to labels length and show a tooltip upon hover?

           xAxes: [{
                stacked: type === 'stacked', 
                scaleLabel: {
                    display: true,
                    labelString: interval ? `${i18n.t('chart.time')} (${i18n.t('chart.' + interval)})` : field.key
                },
                ticks: {
                    autoSkipPadding: 11,
                    maxRotation: 90,
                    minRotation: 0
                }
            }]

Current output looks something like this.

enter image description here

Current solution xD Just modified keys to max length of 18 and made a static exclude list..

    const excludes = ['maakond', 'Maakond', 'district', 'District',
                        'province', 'Province', 'county', 'County'];           

    data.district.data.forEach(el => {
                    excludes.forEach(ex => {
                        el.key = el.key.replace(ex, '');
                    });

                    if(el.key.length > 18) {
                        el.key = el.key.substring(0, 20);
                        el.key = el.key + '.';
                    }
                });
like image 603
kris Avatar asked Dec 23 '25 00:12

kris


1 Answers

Use Chart.scaleService.updateScaleDefaults.

Chart.scaleService.updateScaleDefaults('category', {
    ticks: {
        callback: function (tick) {
            return tick.substring(0, 3);
        }
    }
});

And add this code in your xAxes options.

tooltips: {
    callbacks: {
        title: function (tooltipItems, data) {
            return data.labels[tooltipItems[0].index]
        }
    }
}
like image 72
Jeff Gu Kang Avatar answered Dec 31 '25 19:12

Jeff Gu Kang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!