Christine
Christine

Reputation: 125

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>

Upvotes: 2

Views: 776

Answers (2)

Felix Fungula
Felix Fungula

Reputation: 1

Using Chart.js version 3.x.x or higher, you would use the position property and set it to: position: 'center'. For more details, check the Chart.js documentation.

Example below:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script>
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],
            borderColor: 'blue',
            borderWidth: 2,
        }],
        labels: ['-3', '-2', '-1', '0', '1', '2', '3', '4']
    },
    options: {
        scales: {
            y: {
                                position: 'center',
                suggestedMin: -5,
                suggestedMax: 5,
                ticks: {
                    stepSize: 1
                },
                grid: {
                    color: 'grey',
                    zeroLineColor: 'blue',
                    zeroLineWidth: 2
                }
            },
            x: {
                position: 'center',
                grid: {
                    color: 'grey',
                    zeroLineColor: 'blue',
                    zeroLineWidth: 2
                },
            }
        }
    }
});
</script>

Upvotes: 0

Christine
Christine

Reputation: 125

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.

Upvotes: 1

Related Questions