How to position yAxes labels in chartJS

一曲冷凌霜 提交于 2019-12-23 03:37:51

问题


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

Here's what I've got so far:

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

Here's my chart config:

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


回答1:


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 Demo: https://jsfiddle.net/m5tnkr4n/1/

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.



来源:https://stackoverflow.com/questions/43677197/how-to-position-yaxes-labels-in-chartjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!