[Chartjs]-Chart.js v3: How to align gridlines with stepsizes?

3πŸ‘

βœ…

To have the horizontal grid lines aligned with the y labels, define options.scales.y.grid.offset: false or omit the option.

For the vertical lines from the bottom of the chart up to individual data points, you can use the Plugin Core API. In the afterDraw hook for example, you can draw the lines directly on the canvas using the CanvasRenderingContext2D.

Please take a look at your amended and runnable code and see how it works.

new Chart('chart', {
  type: 'line',
  plugins: [{
    afterDraw: chart => {
      var ctx = chart.ctx;
      ctx.save();
      var xAxis = chart.scales.x;
      var yAxis = chart.scales.y;
      const data = chart.data.datasets[0].data;
      xAxis.ticks.forEach((v, i) => {
        var x = xAxis.getPixelForTick(i);
        var yTop = yAxis.getPixelForValue(data[i]);        
        ctx.strokeStyle = '#aaaaaa';
        ctx.beginPath();
        ctx.moveTo(x, yAxis.bottom);
        ctx.lineTo(x, yTop);
        ctx.stroke();        
      });
      ctx.restore();
    }
  }],
  data: {
    labels: [1, 2, 3, 4, 5, 6, 7],
    datasets: [{
      label: 'My Data',
      data: [65, 59, 80, 81, 56, 55, 68],
      borderColor: '#0a0'
    }]
  },
  options: {
    scales: {
      y: {
        stacked: true,
        grid: {
          display: true,
          drawBorder: false,
          drawOnChartArea: true,
          borderDashOffset: 25,
          borderColor: "#d1d2db",
          borderWidth: 0.8800000000000001,
          color: "#d1d2db",
        },
        min: 0,
        ticks: {
          stepSize: 25,
          beginAtZero: true,
        },
        title: {
          display: false,
          text: "Y axis title",
        },
      },
      x: {
        grid: {
          offset: true,
          display: true,
          drawBorder: false,
          drawOnChartArea: false,
          drawTicks: false,
          tickLength: 0,
          borderColor: "#d1d2db",
          color: "#d1d2db",
        },
      },
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="chart" width="400" height="95"></canvas>

Leave a comment