Search code examples
javascriptchart.js

How do I make the y-axis intersect the x-axis at 0 in chart.js


Is it possible to make Y axis cross X axis at 0 and show labels in the middle of graph using chart.js plugin ?

Now it looks like this:

current

I want it too look something like this:

What i want

My Fiddle / snippet

var ctx = document.getElementById('myChart').getContext('2d');
let chart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      fill: false,
      label: 'Linear',
      data: ['-3', '-2', '-1', '0', '1', '2', '3', '4']
    }],
    labels: ['-3', '-2', '-1', '0', '1', '2', '3', '4']
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          weight: 100,
          suggestedMin: -5,
          suggestedMax: 5,

          stepSize: 1
        },
        plotLines: {
          value: 0,
          width: 2,
          color: 'blue'
        }
      }],
      xAxes: [{
      }]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>


Solution

  • I was able to do the workaround by setting padding for yAxis:

            scales: {
            yAxes: [{
                ticks: {
                    position: top,
                    beginAtZero: false,
                    padding: -225,
                    weight :500,
                    stepSize: 1
                }
    
    
            }],
    

    padding

    Hope it will help someone.