在 ChartJS 中截断画布标签,同时在工具提示中保留完整的标签值标签、画布、提示、完整

2023-09-07 11:34:47 作者:教我如何爱

我有一些条形图的标签很长,它们会影响图表的大小.

I have some bar charts that have really long labels and they affect the size of the charts.

示例:http://jsfiddle.net/norbiu/aqa8w19d/4/

我正在尝试截断图表下方显示的标签,同时在将鼠标悬停在条形上方时保留显示在工具提示中的标签.问题是工具提示和画布标签都从数据结构中的 labels 数组中获取它们的值.截断该值将在两个位置显示缩短的版本.

I'm trying to truncate the labels that show up under the chart while keeping the label that shows up in the tooltips when hovering over a bar. The problem is that the tooltips and the canvas labels both get their values from the labels array in the data structure. Truncating the value will show the shortened version in both locations.

sales: ko.observable({
    labels: ['A really really long label', 'Another long labe', 'A third label that is long', 'Q4', 'Q5', 'Q6'],
    datasets: [{
        label: 'Helados',
        fillColor: '#152491',
        data: [70, 32, 6, 23, 63, 43]
    }]
}),

文档对此一无所知.有什么想法吗?

The documentation has nothing on this. Any ideas?

推荐答案

在 Chart JS V2 中,您可以截断传递选项对象的标签.您还可以自定义工具提示.

In Chart JS V2 you can truncate labels passing the options object. Also you can customize the tooltips.

options:{
    scales: {
        xAxes: [{
            ticks: {
                callback: function(value) {
                    return value.substr(0, 10);//truncate
                },
            }
        }],
        yAxes: [{}]
    },
    tooltips: {
        enabled: true,
        mode: 'label',
        callbacks: {
            title: function(tooltipItems, data) {
                var idx = tooltipItems[0].index;
                return 'Title:' + data.labels[idx];//do something with title
            },
            label: function(tooltipItems, data) {
                //var idx = tooltipItems.index;
                //return data.labels[idx] + ' €';
                return tooltipItems.xLabel + ' €';
            }
        }
    },
}