Dan
Dan

Reputation: 416

Different gridline steps on chart js line chart

I have a line chart with a y axis scale that has ticks with a step size of 5, I would like to have the gridlines have a step/interval of 1. I can't see an obvious way to do it, is there anyway to achieve this in chart.js?

Thanks in advance!

Upvotes: 4

Views: 8427

Answers (1)

jordanwillis
jordanwillis

Reputation: 10705

Unfortunately, with the current Chart.js API, there is no clean way to configure gridline placement independent from tick placement. In other words you cannot configure an axis to show a tick every 5 steps while still showing gridlines every 1 step.

Even though there is no clean way, there is however, still a way to get the behavior your after.

The below configuration will give you the desired results, but the only drawback is the gridlines still extend beyond the axis for the hidden tick labels (e.g. it looks a little funny).

var chartInstance = new Chart(ctx, {
  type: 'line',
  data: data,
  options: {
    scales: {
      yAxes: [{
        ticks: {
          stepSize: 1
        },
        callback: function(value, index, values) {
         if (value % 5 === 0) {
           return value;
         } else {
           return ' ';
         }
       },
      }]
    }
  }
});

Here is a working example via codepen.

Upvotes: 8

Related Questions