[Chartjs]-Specific grid line in X axis in ChartJs

5πŸ‘

βœ…

Sure, you simply need to create a custom callback on the xAxes and return null for all the grid lines you want to filter out – leaving the single grid line you require in your chart.

e.g.

var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'My First dataset',
      backgroundColor: 'rgb(255, 99, 132)',
      borderColor: 'rgb(255, 99, 132)',
      data: [0, 10, 5, 2, 20, 30, 45]
    }]
  },

  // Configuration options go here
  options: {
    scales: {
      xAxes: [{
        ticks: {
          beginAtZero: true,
          callback: function(value, index, values) {
            // where 3 is the line index you want to display
            return (index == 3) ? "" : null;
          }
        }
      }]
    }
  }
});

Working example: https://jsfiddle.net/fraser/kuwh3nzs/

0πŸ‘

The color property in the grid has the support JS functions and then using the context you can give different colors to different grid lines.
https://www.chartjs.org/docs/latest/samples/scale-options/grid.html

-1πŸ‘

I found a solution that works for hiding the grid lines in a Line chart.

Set the gridLines color to be the same as the div’s background color.

var options = {
scales: {
    xAxes: [{
        gridLines: {
            color: "rgba(0, 0, 0, 0)",
        }
    }],
    yAxes: [{
        gridLines: {
            color: "rgba(0, 0, 0, 0)",
        }   
    }]
}

}

or use

var options = {
scales: {
    xAxes: [{
        gridLines: {
            display:false
        }
    }],
    yAxes: [{
        gridLines: {
            display:false
        }   
    }]
}
}

Leave a comment