Chart.js 3.7.1 折线图 - 如何在 y 轴上单独设置每个标签的格式?

Chart.js 3.7.1 Line Chart - How can I format each label individually on the y axis?

我有一个折线图。数据介于 -10 和 10 之间。 y 轴上的标签是正确的(-10 到 10 递增 1)。

我需要基于一组颜色使每个标签的颜色不同。标签数和颜色数都是21(-10到10包括0)。 我真的很想要一个渐变的 'strip',这样每个标签都在颜色的垂直位置。

我在代码中试过这个,但了解到 html 在图表中不可用:

options: {
    responsive: true,
    plugins: {
        title: {
            display: true,
            text: 'Topic Sentiment'
        }
    },
    scales: {
        y: {                    
            title: {
                display: true,
                text: 'Sentiment Scores'
            },
            min: -10,        
            max: 10,
            ticks: {
                stepSize: 1,
                callback: function(value, index, ticks) {                           
                    return value + " <div style='height:100%; width:8px; background:" + arColors[index] + ";' ></div>"
                }
            }
        }
    },
    onClick: (e, activeEls) => {
        var oChart = e.chart, label = "";
    }           
}

这就是我的意思。 y 渐变被添加到 Photoshop 中的实际图表图像中。
我可以做这样的事吗?

您可以将 y.ticks.color 定义为 rgb 颜色的数组。这些颜色可以即时生成。

受此启发amazing answer from Pevara,我想出了以下解决方案:

function hslToRgb(h, s, l) {
  var r, g, b;
  if (s == 0) {
    r = g = b = l; // achromatic
  } else {
    function hue2rgb(p, q, t) {
      if (t < 0) t += 1;
      if (t > 1) t -= 1;
      if (t < 1 / 6) return p + (q - p) * 6 * t;
      if (t < 1 / 2) return q;
      if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
      return p;
    }
    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
    var p = 2 * l - q;
    r = hue2rgb(p, q, h + 1 / 3);
    g = hue2rgb(p, q, h);
    b = hue2rgb(p, q, h - 1 / 3);
  }
  return [Math.floor(r * 255), Math.floor(g * 255), Math.floor(b * 255)];
}

function yValueToRGB(hue) {
  var rgb = hslToRgb(hue, 1, .5);
  return 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
}

const yTickColors = Array.from(Array(21).keys()).map(v => yValueToRGB(v / 60));

new Chart('canvas', {
  type: 'line',
  data: {
    labels: ['A', 'B', 'C', 'D', 'E', 'F'],
    datasets: [{
        label: 'Dataset 1',
        data: [3, 9, 7, 5, 9, 2],
        backgroundColor: 'rgba(255, 99, 132, 0.2)',
        borderColor: 'rgb(255, 99, 132)',
        fill: false
      },
      {
        label: 'Dataset 2',
        data: [1, 2, -3, -5, -2, 1],
        backgroundColor: 'rgba(255, 159, 64, 0.2)',
        borderColor: 'rgb(255, 159, 64)'
      }
    ]
  },
  options: {
    scales: {
      y: {
        max: 10,
        min: -10,
        ticks: {
          stepSize: 1,
          autoSkip: false,
          color: yTickColors
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js"></script>
<canvas id="canvas"></canvas>