Chart.js:如果 > 或 < 0,如何设置多种颜色以勾选 y 轴

Chart.js: how to set multiple color to tick of y axes if > or < 0

如何设置 y 轴的多个刻度颜色:如果 < 0 则为红色,如果 > 0 则为绿色? 提前Tnx

scales: {
    yAxes: [{
        ticks: {
            fontColor: ["Red","Black","Green"],
            callback: function(value,index,values) {
                if (value == 0 ) {
                    return black color;
                } else if (value > 0) {
                    return green color;
                } else {
                    return red color;
                }
            },
       }]
   }

您必须更新到 lib 的 v3,然后您可以像这样使用可编写脚本的选项:

  options: {
    scales: {
      y: {
        ticks: {
          color: (tick) => (tick.tick.value < 0 ? 'red' : tick.tick.value > 0 ? 'green' : '#666')
        }
      }
    }
  }

实例:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [-12, 19, 3, -5, 2, 3],
      borderWidth: 1,
      borderColor: 'red',
      backgroundColor: 'red'
    }]
  },
  options: {
    scales: {
      y: {
        ticks: {
          color: (tick) => (tick.tick.value < 0 ? 'red' : tick.tick.value > 0 ? 'green' : '#666')
        }
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
    <canvas id="chartJSContainer" width="600" height="400"></canvas>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.3.0/chart.js"></script>
</body>