[Chartjs]-How to set chart.js grid color for line chart

7👍

The easiest way to do this is to use the chartjs-plugin-annotation plugin and configure 3 box annotations bound to your Y axis (each box would have a different color).

Here is an example below (and you can see it in action with this codepen).

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
      label: 'Points',
      data: [
        {x: 0, y: 2},
        {x: 1, y: 3}, 
        {x: 2, y: 2},
        {x: 1.02, y: 0.4},
        {x: 0, y: -1}
      ],
      backgroundColor: 'rgba(123, 83, 252, 0.8)',
      borderColor: 'rgba(33, 232, 234, 1)',
      borderWidth: 1,
      fill: false,
    }],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js - Gridline Background',
    },
    scales: {
      xAxes: [{
        type: 'linear',
        position: 'bottom',
        ticks: {
          min: -1,
          max: 8,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 1
        }
      }],
      yAxes: [{
        afterUpdate: function(scaleInstance) {
          console.dir(scaleInstance);
        },
        ticks: {
          min: -2,
          max: 4,
          stepSize: 1,
          fixedStepSize: 1,
        },
        gridLines: {
          color: 'rgba(171,171,171,1)',
          lineWidth: 0.5
        }
      }]
    },
    annotation: {
      annotations: [{
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  1,
        yMax: 4,
        borderColor: 'rgba(255, 51, 51, 0.25)',
        borderWidth: 2,
        backgroundColor: 'rgba(255, 51, 51, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -1,
        yMax: 1,
        borderColor: 'rgba(255, 255, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(255, 255, 0, 0.25)',
      }, {
        type: 'box',
        yScaleID: 'y-axis-0',
        yMin:  -2,
        yMax: -1,
        borderColor: 'rgba(0, 204, 0, 0.25)',
        borderWidth: 1,
        backgroundColor: 'rgba(0, 204, 0, 0.25)',
      }],
    }
  }
});

It’s important to note that the annotations are painted on top of the chart, so your annotation color needs to contain some transparency to see the stuff behind it.

There is no problem using this plugin with ng2-charts. Just add the source in a <script> in your app’s html file and add the annotation property into your options object. Here is an Angular2 / ng2-charts example demonstrating how to use the annotations plugin.

Leave a comment