Chart.js: Automatic scaling not starting at zero

Created on 20 Jul 2017  ·  5Comments  ·  Source: chartjs/Chart.js

Hi, I have the following code for a bar chart that has a very simple data set of integers:

<html>
  <head>
    <title>ChartJs Test</title>
    <script src="http://www.chartjs.org/dist/2.6.0/Chart.bundle.js"></script>
  </head>

  <body>
      <div style="width: 75%">
        <canvas id="canvas"></canvas>
      </div>

      <script>
        var barChartData = {
          labels: ["January", "February", "March"],
          datasets: [{
            label: 'Dataset 1',
            data: [2, 3, 1]
          }]
        };

        window.onload = function() {
          var ctx = document.getElementById("canvas").getContext("2d");

          window.myBar = new Chart(ctx, {
            type: "bar",
            data: barChartData
          });
        };

      </script>
  </body>
</html>

You can see in the js fiddle that there are two visual issues. Firstly the scale does not start at zero giving a false impression of the data, and also the scale on the left has decimals places even though the data is only integers. Why is this? Am I missing something? Cheers

support

Most helpful comment

@burt202 You can add beginAtZero to your scales configuration, which will allow you to specify that the scale starts at 0. Here is an updated jsfiddle: https://jsfiddle.net/9bgeu5rx/1/

options: {
     scales: {
         yAxes: [{
             ticks: {
                 beginAtZero: true
             }
         }]
     }
 }

All 5 comments

@burt202 You can add beginAtZero to your scales configuration, which will allow you to specify that the scale starts at 0. Here is an updated jsfiddle: https://jsfiddle.net/9bgeu5rx/1/

options: {
     scales: {
         yAxes: [{
             ticks: {
                 beginAtZero: true
             }
         }]
     }
 }

Thanks for the reply. I did know about beginAtZero option but the data feeding the chart is dynamic so I cant really use it. Is there any other way of achieving this? I suppose I could analyse the data coming in to see if it has values close to 0 and only set it when it is?

@burt202 you would have to detect that on your end before feeding the data to Chart.js. Using the min and max properties could also help.

OK thanks. Giving this more thought, i think the issue is not necessarily to do with starting at zero because you can change the data to be 20, 21, 22 and you would have the same problem (scale would start at 20). I appreciate its difficult to add in automatic lower and upper scale values that is not one of the data values because its hard to know the context of the data, I think I was just surprised that this was the default. Closing for now as I'll work out a way of using the options to dynamically achieve this. Cheers

https://github.com/chartjs/Chart.js/issues/4537#issuecomment-316820751

This solution is not working

Was this page helpful?
0 / 5 - 0 ratings