Chris
Chris

Reputation: 11

Chart.js beginAtZero doesn't work

I've got problems with Chart.js because the bars aren't starting at zero even though I set the beginAtZero argument.

I tried multiple ways for the right position of the code, but it doesn't seem to work.

Does anyone have an idea of how to fix my problem?

Here is the code:

var chartdata = {
  labels: answer,
  datasets: [{
      label: 'Count',
      backgroundColor: 'rgba(200, 200, 200, 0.75)',
      borderColor: 'rgba(200, 200, 200, 0.75)',
      hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
      hoverBorderColor: 'rgba(200, 200, 200, 1)',
      data: count
    }
  ]
};

var options = {
  scales: {
    yAxes: [{
      ticks: {
        beginAtZero: true
      }
    }]
  }
};

var ctx = $("#mycanvas");

var barGraph = new Chart(ctx, {
  type: 'bar',
  data: chartdata
  options: options
});

Upvotes: 1

Views: 4241

Answers (1)

Tot Zam
Tot Zam

Reputation: 8746

It looks like you are using Chart.js v1 instead of v2.

First, update your the Chart.js code to v2, preferably the latest version.

Then, change the following code:

var barGraph = new Chart(ctx, {
    type: 'bar',
    data: chartdata
    options: options
});

to:

var barGraph = Chart.Bar(ctx, {
  data: chartdata,
  options: options
});

beginAtZero: true should then work as expected.

Working JSFiddle: https://jsfiddle.net/ko54hp6n/


For an alternative to beginAtZero: true, you can also use the min: 0 ticks configuration option to start the bar axis at zero:

var options = {
  scales: {
    yAxes: [{
      ticks: {
        min: 0
      }
    }]
  }
}

Working JSFiddle: https://jsfiddle.net/ko54hp6n/1/

Upvotes: 2

Related Questions