John McGowan John McGowan - 5 days ago 5
Javascript Question

How to set lower limit for the highest value being displayed on Y Axis?

I have a chart.js line graph whereby the Y-value is a percentage from 0-100 and the X-axis represents time in seconds for the past minute. The chart is populated using live data from a socket connection that updates every five seconds.

I'm running into a problem with the Y-Axis steps being generated dynamically by chart.js. For the most part, everything is great and the Y-Axis scales according to the range of data currently being displayed. However, when the percentage is 0% or when it falls between 0 and 1, for example .654%, the Y-Axis will show display a min value of 0 and a max value of 1%. Therefore, the chart is misleading as it appears that the percentage is a high one when in fact it is less than 1%.

enter image description here

So my question is: how do I set a minimum value for the max value being displayed along the Y-axis?

(now before you jump to conclusions and drop a line about the stepSize property, I have tried setting the stepSize to values like 1 and 3. The problem with that, is that when the percentage values jump to 75% or above, the large number of labels required (75/3 or 75/1) ends up making the labels illegible)

Answer

You are looking for the suggestedMax tick option for the y-axis. Use it like this:

options: {
  scales: {
    yAxes: [{
      ticks: {
        suggestedMax: 60
      }
    }]
  }
}

This tick value will be used as the maximum tick of the y-axis, provided that all data values are lower than this. If a data value is higher than this tick value, then a higher tick value will be automatically calculated and used instead. From the docs:

suggestedMax

User defined maximum number for the scale, overrides maximum value except for if it is lower than the maximum value.

You may see it in action here and below.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: 'Percentage',
      data: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          suggestedMax: 60
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

Comments