如何在chartJS中定位yAxes标签

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

我想将 y 轴刻度标签对齐 chartJS 中的刻度.

I want to align the y-axis tick labels above the ticks in chartJS.

这是我目前所得到的:

我想要刻度标签上方的刻度标签 0M20M40M.像这样的:

I want the tick labels 0M, 20M, and 40M above the tick labels. Something like this:

这是我的图表配置:

new Chart(ctx, {
    type: 'bar',
    data,
    options: {
      ...
      scales: {
        xAxes: [{ ... }],
        yAxes: [{
          stacked: true,
          position: 'right',
          gridLines: {
            drawBorder: false
          },
          ticks: {
            maxTicksLimit: 3
          }
        }]
      }
    }
  })

我无法在图表选项中找到任何选项来执行此操作.请帮忙

I'm not able to find any option in the chart options to do such a thing. Please help

推荐答案

您可以通过在 options 配置中添加 animation 来做到这一点:

You can do this by adding an animation to the options config:

options: {
    animation: {
        duration: 1,
        onComplete: function() {
            var controller = this.chart.controller;
            var chart = controller.chart;
            var yAxis = controller.scales['y-axis-0'];

            yAxis.ticks.forEach(function(value, index) {
                var xOffset = chart.width - 40;
                var yOffset = ((chart.height - 60) / 2 * index) + 15;
                ctx.fillText(value + 'M', xOffset, yOffset);
            });   
        }
    }
}

JSFiddle 演示:https://jsfiddle.net/m5tnkr4n/1/

JSFiddle Demo: https://jsfiddle.net/m5tnkr4n/1/

您可能需要调整 xOffsetyOffset 中的硬编码数字.这些数字将取决于图表的高度和宽度,以及您在画布区域中显示的功能.例如,如果您删除 xAxes 刻度标签,您需要减小 -60,因为这会使图表略短./2 有效,因为您将 maxTicksLimit 设置为 3.

You may need to adjust the hardcoded numbers in the xOffset and yOffset. These numbers will depend on the height and width of your chart, as well as what features you are displaying the in the canvas area. For example, if you remove the xAxes tick labels, you many need to decrease the -60 since that will make the chart slightly shorter. / 2 works since you set the maxTicksLimit to 3.

相关文章