ChartJS 在刻度之间放置 y 轴标签

2023-12-06

I have the following graph: enter image description here

However, i'd like to shift the y axis labels to be the following:enter image description here

是否可以使用 ChartJS 将 y 轴标签移动到刻度线之间,如上面的示例图片所示?

功能类似于options.scales.yAxes[].ticks.position选项,但目前它定义为in the x direction for the y axis,因为我需要它在 y 轴的 y 方向。更好的是,自动居中。


不幸的是,目前 ChartJS 中没有内置方法来实现这一点。

您宁愿需要创建一个图表插件来实现这一目标。

plugins: [{
   beforeDraw: function(chart) {
      var ctx = chart.ctx;
      var yAxis = chart.scales['y-axis-0'];
      var tickGap = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
      yAxis.options.ticks.fontColor = 'transparent'; // hide original tick
      // loop through ticks array
      Chart.helpers.each(yAxis.ticks, function(tick, index) {
         if (index === yAxis.ticks.length - 1) return;
         var xPos = yAxis.right;
         var yPos = yAxis.getPixelForTick(index);
         var xPadding = 10;
         // draw tick
         ctx.save();
         ctx.textBaseline = 'middle';
         ctx.textAlign = 'right';
         ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
         ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
         ctx.restore();
      });
   }
}]

note: this will hide the first tick (which begins at 0)

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var barChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ['Jan', 'Feb', 'Mar'],
      datasets: [{
         label: 'BAR',
         data: [10, 20, 30],
         backgroundColor: 'rgba(0, 119, 204, 0.5)'
      }]
   },
   options: {
      responsive: false,
      scales: {
         yAxes: [{
            ticks: {
               beginAtZero: true
            }
         }]
      }
   },
   plugins: [{
      beforeDraw: function(chart) {
         var ctx = chart.ctx;
         var yAxis = chart.scales['y-axis-0'];
         var tickGap = yAxis.getPixelForTick(1) - yAxis.getPixelForTick(0);
         yAxis.options.ticks.fontColor = 'transparent'; // hide original tick
         // loop through ticks array
         Chart.helpers.each(yAxis.ticks, function(tick, index) {
            if (index === yAxis.ticks.length - 1) return;
            var xPos = yAxis.right;
            var yPos = yAxis.getPixelForTick(index);
            var xPadding = 10;
            // draw tick
            ctx.save();
            ctx.textBaseline = 'middle';
            ctx.textAlign = 'right';
            ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
            ctx.fillText(tick, xPos - xPadding, yPos + tickGap / 2);
            ctx.restore();
         });
      }
   }]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx" height="200"></canvas>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ChartJS 在刻度之间放置 y 轴标签 的相关文章

随机推荐