如何在charts.js中更改主要y轴标签的方向?

时间:2020-09-08 12:22:05

标签: chart.js

这不是我想要的,用红色圆圈圈出:

Unwanted - vertically orientated y-axis label

然后用绿色圆圈圈住,这是我想要的:

Wanted - horizontally orientated y-axis label

也就是说,我只是简单地更改y轴标签的方向,使其与图表中的所有其他文本一样为水平。

我看了文档的Scale Title Configuration部分,但是那里没有任何线索。另外,y轴标题显示在画布上,因此我无法使用CSS控制其方向。

那么,如何更改chart.js中主要y轴标签的方向?

1 个答案:

答案 0 :(得分:1)

作为一种解决方法,您可以添加第二个y轴并按如下所示对其进行定义:

{
  gridLines: {
    display: false
  },
  ticks: {
    maxTicksLimit: 3,
    callback: (value, index) => index == 1 ? 'Scale Label' : ''
  }
}

请查看下面的代码片段,并查看其工作原理。

new Chart(document.getElementById('myChartAxis'), {
  type: 'line',
  data: {
    labels: ['A', 'B', 'C', 'D'],
    datasets: [{
        label: 'WARNINGS',
        data: [1, 2, 3, 2],
        borderColor: 'rgb(255, 159, 64)',
        backgroundColor: 'rgba(255, 159, 64, 0.2)',
        fill: false
      },
      {
        label: 'ERRORS',
        data: [1, 2, 1, 3],
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        fill: false
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
          ticks: {
            beginAtZero: true,
            stepSize: 1
          }
        },
        {
          gridLines: {
            display: false
          },
          ticks: {
            maxTicksLimit: 3,
            callback: (value, index) => index == 1 ? 'Scale Label' : ''
          }
        }
      ]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChartAxis" height="90"></canvas>

相关问题