如何在 chartJs 中以不同方式设置特定网格线的样式?

How to style specific gridlines differently in chartJs?

我正在使用 chartJS 绘制气泡图,x 轴 运行 从 -5 到 +5,y 轴 运行 从 -5 到 +5。我能够使用

更改网格线样式
x: {
    grid: {
      borderDash: [2, 10],
      lineWidth: 1,
      color: `#000`,
    },

得到这个结果。

my chart output so far

我需要将 X 轴和 Y 轴都设置为 0 才能显示为实心粗体。有没有办法在特定的刻度点设置网格线的样式?

想要的结果是这样...

desired chart styling

borderDash 选项不可编写脚本,因此要实现此行为,您需要使用自定义插件来绘制默认网格线:

const zeroZeroLines = {
  id: 'zeroZeroLines',
  beforeDatasetsDraw: (chart, args, opts) => {
    const {
      ctx,
      chartArea: {
        top,
        bottom,
        left,
        right
      },
      scales: {
        x,
        y
      }
    } = chart;

    const color = opts.color || 'black';
    const width = opts.width || 1;

    ctx.beginPath();

    ctx.lineWidth = width;
    ctx.strokeStyle = color;

    ctx.moveTo(x.getPixelForValue(0), bottom);
    ctx.lineTo(x.getPixelForValue(0), top);

    ctx.moveTo(left, y.getPixelForValue(0));
    ctx.lineTo(right, y.getPixelForValue(0));

    ctx.stroke();
  }
}

const options = {
  type: 'bubble',
  data: {
    datasets: [{
      label: '# of Votes',
      data: [{
        x: -4,
        y: 0,
        r: 4
      }, {
        x: 1,
        y: -3,
        r: 10
      }, {
        x: 3,
        y: 3,
        r: 20
      }, {
        x: 0,
        y: 0,
        r: 20
      }],
      backgroundColor: 'pink'
    }]
  },
  options: {
    scales: {
      x: {
        min: -5,
        max: 5,
        grid: {
          borderDash: [2, 2]
        }
      },
      y: {
        min: -5,
        max: 5,
        grid: {
          borderDash: [2, 2]
        }
      }
    },
    plugins: {
      zeroZeroLines: {
        color: 'black',
        width: 1
      }
    }
  },
  plugins: [zeroZeroLines]
}

const 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.5.0/chart.js"></script>
</body>