Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJS: How to set fixed Y axis max and min

I have a line chart which I'm trying to set a fixed max and min values. I have tried the other suggestions found on SO, but it still doesn't work. My chart keeps re-setting the max and min values depending on the incoming data.

Here's my current options that I pass to my Line chart:

var options = {
        responsive: true,
        animation: false
};

I tried those settings too:

var options = {
    scales: {
        animation: false,
        yAxes: [{
            display: true,
            ticks: {
                suggestedMin: -1,
                suggestedMax: 1
            }
        }]
    }
};

Any idea what I'm doing wrong?

Thanks!

like image 901
Nayzer Avatar asked Dec 19 '16 05:12

Nayzer


People also ask

How do you change the Y axis range in Chartjs?

For chart. js V2 (beta), use: var options = { scales: { yAxes: [{ display: true, ticks: { suggestedMin: 0, // minimum will be 0, unless there is a lower value. // OR // beginAtZero: true // minimum value will be 0. } }] } };

How do you find the maximum and minimum value of Y axis?

We can do that by assigning a value to the max property to the y-axis. We are using beginAtZero property to set the min value of y-axis to 0. And max property to set the maximum value to y-axis.

How do you set the y axis values?

Add or change the position of vertical axis labelClick the chart, and then click the Chart Layout tab. Under Axes, click Axes > Vertical Axis, and then click the kind of axis label that you want.


2 Answers

To fix min and max value for yAxes scale use the below code.

options:{
            scales: {
                yAxes : [{
                    ticks : {
                        max : 1,    
                        min : -1
                    }
                }]
            }
        }

suggestedMax will only works when incoming data is lower than suggestedMax value. suggestedMin will works only when incoming data is greater than suggestedMin value.

like image 75
Sanjay Dutt Avatar answered Oct 16 '22 00:10

Sanjay Dutt


For Chart.js version < 3.0:

From Sanjay Dutt's answer:

options:{
  scales: {
    yAxes : [{
      ticks : {
        max : 1,    
        min : -1
      }
    }]
  }
}

For Chart.js version >= 3.0:

Due to breaking changes in version 3.X, the above mentioned answer doesn't work anymore. Chart.js created a Migration Guide to solve the upcoming problems. The minimum and maximum values can now be configured directly to the options.scales:

options : {
    scales : {
        y : {
            min: -1,
            max: 1,
        }
    }
}
like image 41
mhellmeier Avatar answered Oct 15 '22 22:10

mhellmeier