【问题标题】:How to fix bars in Chart.js with long labels如何修复 Chart.js 中带有长标签的条形图
【发布时间】:2018-09-29 13:53:22
【问题描述】:

我在我的应用程序中使用 Chart.js(版本:2.7.2),结果行中的一些标签相当长

        var barCanvas = document.getElementById("canvasVoteNames");
        var ctx = barCanvas.getContext('2d');

        var numberWithCommas = function(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        };
        var self = this;
        var myChart = new Chart(ctx, {  // stacked bar report https://jsfiddle.net/sdfx/hwx9awgn/
            type: 'bar',
            data: {
                labels:monthsXCoordItems,
                datasets: [

                    {
                        label: 'Correct Votes',
                        data: voteValuesCorrect,
                        borderWidth: 1,           // The stroke width of the bar in pixels.

                        backgroundColor : formatColor('#05b932'), //rgba(0, 0, 0, 0.1), // The fill color of the bar. See Colors
                        borderColor: formatColor('#05b932'),// rgba(255, 0, 0, 0.1) // The color of the bar border.

                        hoverBackgroundColor : formatColor('#05b932'),   // The fill colour of the bars when hovered.
                        hoverBorderColor: formatColor('#05b932'),        //    The stroke colour of the bars when hovered.
                        hoverBorderWidth : 1                             //    The stroke width of the bars when hovered.
                    },

                    {
                        label: 'Incorrect Votes',
                        data: voteValuesNoneCorrect,
                        borderWidth: 1,           // The stroke width of the bar in pixels.

                        backgroundColor : formatColor('#b1a19a'), //rgba(0, 0, 0, 0.1), // The fill color of the bar. See Colors
                        borderColor: formatColor('#b1a19a'),// rgba(255, 0, 0, 0.1) // The color of the bar border.
                        hoverBackgroundColor : formatColor('#b1a19a'),   // The fill colour of the bars when hovered.
                        hoverBorderColor: formatColor('#b1a19a'),        //    The stroke colour of the bars when hovered.
                        hoverBorderWidth : 1                             //    The stroke width of the bars when hovered.
                    },

                ]
            },

            options: { // options of Report By Vote Names
                animation: {
                    duration: 10,
                },

                tooltips: { // tooltip text of Report By Vote Days ( 'bar' report )
                    mode: 'label',
                    callbacks: {
                        label: function(tooltipItem, data) {
                            return data.datasets[tooltipItem.datasetIndex].label + ": " + numberWithCommas(tooltipItem.yLabel);
                        }
                    }
                }, // tooltips: { // tooltip text of Report By Vote Days ( 'bar' report )

                scales: { // options for x and y scales
                    xAxes: [{
                        stacked: true,    // Stacked bar charts can be used to show how one data series i
                        gridLines: { display: false },
                    }],
                    yAxes: [{
                        stacked: true,  // Stacked bar charts can be used to show how one data series i
                        ticks: {
                            callback: function(value) { // on Y scale show only integer without decimals
                                if (Math.floor(value) === value) {
                                    return value;
                                }
                            },  // callback: function(value) { return numberWithCommas(value); },
                        },
                    }],
                }, // scales: { // options for x and y scales
                legend: {display: true}
            } // options: { // options of Report By Vote Names

        }); // var myChart = new Chart(ctx, {  // stacked bar report https://jsfiddle.net/sdfx/hwx9awgn/

}

我得到的图表就是我需要的 https://imgur.com/a/n1SsW7w 但是对于任何酒吧都有长标签,它看起来并不好,我没有找到是否有办法以某种方式修复它? 为什么标签的边距很大,而不是相对条?

xAxes 或附加图例的一些选项?

谢谢!

【问题讨论】:

  • 对不起,我还在寻找一些决定。我在谷歌上搜索并找到了几个示例,但它们都带有短标签,并且没有类似我的问题......没有想法?
  • 我找到了一个类似的例子并修改了一些标签以重复我的问题:jsfiddle.net/hwx9awgn/1259 xAxes 上的一些标签根本没有显示:实际上 1,3,5... 显示的标签可以是任何决定?

标签: javascript chart.js


【解决方案1】:

您在 JSFiddle 中使用的是 ChartJs 2.1.3 版,它似乎无法处理多行标签

您可以通过以下解决方案使用多行标签:

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"];

你可以用数组替换标签,数组的每个元素都会被视为一个新行(见JSFiddle):https://jsfiddle.net/cyuwxh3q/


如果您的标签是动态生成的,您可以使用图表配置中的插件将它们拆分:

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

此函数会将每个标签转换为长度小于或等于给定值(此处为 5)的元素数组(参见 JSFiddle):https://jsfiddle.net/jhr5nm17/


这是处理长标签的两种简单方法,将它们替换为多行标签,希望对您有所帮助。

【讨论】:

  • 谢谢,我找的就是这个!还有一些参数可以更改 xAxes 上条形元素之间的宽度?
  • 您可以在选项中添加 barThickness 属性:{ scales: { xAxes: [{ barThickness: value, ... }] } }
  • 我又发现了一个问题:我通过单击切片打开了弹出对话框并定义单击了哪个切片,我将项目的 ID/名称保存在数组中并按标签名称进行搜索。现在这不起作用,因为标签的文本是数组。当然我可以通过串联的数组字符串来做,但是如果有更好的决定,比如用户为任何切片定义的标签?
  • 您需要覆盖图表,有关更多信息,请参阅此问题:stackoverflow.com/questions/28377145/…。如果这不适合您,请考虑编写一个新问题以获得更多答案。如果此处提供的答案帮助您解决了问题,请考虑接受。
  • @Ivan 如果这个答案解决了你的问题,请不要忘记接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-10
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-18
  • 1970-01-01
相关资源
最近更新 更多