使标签在图表 js 中响应

2022-01-22 00:00:00 charts javascript chart.js

我很难使 y 轴上的标签具有响应性.我希望标签移动到多行并在空间不足时具有响应式字体大小.我正在使用 chart.js 数据标签用于在水平条形图顶部标记的库.由于外部图表容器,标签也被隐藏了.

I'm having a hard time making the labels in the y-axis responsive.I want the labels to move to multiple lines and have responsive font sizes when the space is not enough.I'm using the chart.js datalabels library for labelling on top of horizontalBar Graph.Also the labels are getting hidden due to the outer chart container.

var chart = new Chart('ctx', {
    type: 'horizontalBar',
    data: {
        labels: ["Something something something", "blah blah..", "blah blah..","Something something something"],
        datasets: [{
            data: [6, 87, 56,25,100,65],
            backgroundColor: "#4082c4"
        }]
    },
    options:{
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            datalabels: {
                color: 'black',
                anchor: "end",
                align: "right",
                offset: 20,
                display: function (context) {
                    return context.dataset.data[context.dataIndex];
                },
                font: {
                    weight: 'bold',
                    size: 26
                },
                formatter: Math.round
            }
        },
        legend: {
            "display": false
        },
        tooltips: {
            "enabled": false
        },
        scales: {
            yAxes: [{
                barPercentage: 1.0,
                gridLines: {
                    display: false
                },
                ticks: {
                    fontSize: 20,
                    beginAtZero: true,
                }
            }],
            xAxes: [{
                gridLines: {
                    display: false
                },
                ticks: {
                    min: 0,
                    max: 100,
                    stepSize: 20
                }
            }]
        }
    }
    })

栏右侧的数字也会被剪掉.我希望图表水平居中.在浏览器中,图表看起来像这样-小提琴链接:-https://jsfiddle.net/24wdpfxL/

The numbers in the right side of the bar also gets clipped of.I want the chart to be at the center horizontally.In the browser the chart looks like this- Link to the fiddle:-https://jsfiddle.net/24wdpfxL/

推荐答案

你可以这样做,但它有点 hack-y.

You can do this, but it's a bit hack-y.

首先是数据标签.在 datalabels 配置部分,您可以尝试以下操作:

First the data labels. In the datalabels config section, you can try something like:

            /* Adjust data label font size according to chart size */
            font: function(context) {
                var width = context.chart.width;
                var size = Math.round(width / 32);

                return {
                    weight: 'bold',
                    size: size
                };
            }

根据需要更改大小计算.

Change the size calculation as necessary.

对于 y 轴标签,有一个答案 这里,但显然自 Chart.js 2.7.0 以来,该行:

For the y-axis labels, there's an answer here, however apparently since Chart.js 2.7.0, the line:

c.scales['y-axis-0'].options.ticks.fontSize

..应该改为:

c.scales['y-axis-0'].options.ticks.minor.fontSize

(ref)

所以要根据图表高度缩放 ​​y 轴标签字体大小,它可能看起来像:

So to scale the y-axis labels font size according to chart height, it might look like:

plugins: [{
    /* Adjust axis labelling font size according to chart size */
    beforeDraw: function(c) {
        var chartHeight = c.chart.height;
        var size = chartHeight * 5 / 100;
        c.scales['y-axis-0'].options.ticks.minor.fontSize = size;
    }
}]

注意:这需要将maintainAspectRatio:"设置为true".

Note: This requires "maintainAspectRatio:" to be set to "true".

不过还有一个问题,那就是图表中包含 y 轴标签的部分即使在调整大小时也会保持相同的像素宽度.

There's still one problem however, and that's that the part of the chart containing the y-axis labels will remain at the same pixel width even when resized.

我们还需要调整此区域的大小以使其保持在整个图表宽度的恒定百分比,例如40%,而不是固定的像素宽度(添加到 yAxes 配置部分):

We need to also resize this area to keep it at a constant % of the overall chart width, e.g. 40%, instead of a fixed pixel width (added to yAxes config section):

        /* Keep y-axis width proportional to overall chart width */
        afterFit: function(scale) {
            var chartWidth = scale.chart.width;
            var new_width=chartWidth*0.4;

            scale.width = new_width;
        }

(您可能不会注意到这是原始示例的问题,因为有一条过大的线似乎会导致 y 轴宽度在窗口放大时继续扩大.但是当标签不溢出时,然后宽度保持不变,除非使用上述内容.)

(You might not notice this as a problem with your original example, since there is a oversized line that seems to cause the y-axis width to keep expanding when the window is enlarged. But when the labels don't overflow, then the width stays constant unless the above is used.)

完整的 jsFiddle:https://jsfiddle.net/0kxt25v3/2/(全屏)

Complete jsFiddle: https://jsfiddle.net/0kxt25v3/2/ (fullscreen)

我不确定将标签包装到下一行,您可能只需要预处理标签以限制每个标签的最大字符数.

I'm not sure about wrapping labels on to the next line, you might just need to pre-process the labels to limit the maximum number of characters per label.

我也没有尝试缩放 x 轴标签字体大小,但将其添加到beforeDraw:"部分应该很容易.

I also haven't attempted to scale the x-axis label font sizes, but it should be easy enough to add it in to the "beforeDraw:" section.

相关文章