[Chartjs]-How to link 2 axes with chartJS?

1๐Ÿ‘

I think there is an error in y scale config. beginAtZero is not an option of ticks but of the scale itself.

y: {
      display:true,
      beginAtZero: true, // <--- move here
      ticks: {
        display: true,
      },
      // to remove the y-axis grid
      grid: {
        drawBorder: false,
        display: false,
      },
    },

Furthermore to be sure that the ticks will not change, you could set min/max options in the axis and stepSize/count in the ticks.

1๐Ÿ‘

Here you can see an plugin (prototype) which is drawing an "X axis" at the same position of 0 Y value.

Some points of attention:

  1. added padding to right of the chart to draw last label
  2. the X axis must be defined but ticks are hidden (you can maintain the grid)
  3. used Chart.js 4.2.0

Sample:

const ctx = document.getElementById('myChart').getContext('2d');
const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
const plugin = {
  id: 'middleAxis',
  beforeDraw(chart) {
    const {ctx, scales} = chart;
    const yAxis = scales.y;
    const xAxis = scales.x;
    const zeroPosition = yAxis.getPixelForValue(0);
    const labelItems = xAxis.getLabelItems();
    ctx.save();
    ctx.beginPath();
    ctx.lineWidth = 1;
    ctx.moveTo(xAxis.left, zeroPosition);
    ctx.lineTo(xAxis.right, zeroPosition)
    ctx.stroke();
    for (const item of labelItems) {
      const {font, label, options} = item;
      const {strokeWidth, strokeColor, textAlign, textBaseline, translation} = options;
      const x = translation[0];
      const y = zeroPosition + font.lineHeight;
      ctx.beginPath();
      ctx.font = font.string;
      ctx.textAlign = textAlign;
      ctx.textBaseline = textBaseline;
      ctx.lineWidth = strokeWidth;
      ctx.strokeStyle = strokeColor;
      ctx.fillText(label, x, y);
      ctx.fill();
    }
    ctx.restore();
  }
};

const myChart = new Chart(ctx, {
  type: 'line',
  plugins: [plugin],
  data: {
    labels,
    datasets: [{
      label: 'ds1',
      data: [1, -2, 3, -4, 5]
     }]
   },
  options: {
    layout: {
      padding: {
        right: 20
      }
    },
    scales: {
      x: {
        display: true,
        grid: {
          drawTicks: false
        },
        ticks: {
          display: false
        }
      }
    }
  }
 });
.myChartDiv {
  max-width: 600px;
  max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.0/dist/chart.umd.min.js"></script>
<html>
  <body>
    <div class="myChartDiv">
      <canvas id="myChart" width="600" height="400"/>
    </div>
  </body>
</html>

Leave a comment