简体   繁体   中英

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

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.

在此处输入图片说明

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 + '.';
                    }
                });

Solution

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]
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM