如何在chartJS中放置yAxes标签

如何在chartJS中放置yAxes标签

本文介绍了如何在chartJS中放置yAxes标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将y轴刻度标签对齐在chartJS的刻度上方

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

这是到目前为止的内容:

Here's what I've got so far:

我想要刻度标签勾号上方的 0M 20M 40M 。像这样的东西:

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

推荐答案

您可以通过在动画上添加动画来实现。 选项配置:

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演示:

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

您可能需要调整 xOffset yOffset 中的硬编码数字。这些数字将取决于图表的高度和宽度,以及在画布区域中显示的功能。例如,如果删除 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.

这篇关于如何在chartJS中放置yAxes标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:33