简体   繁体   中英

Specific grid line in X axis in ChartJs

Is there a way to place a single grid line at specific XAxis value?

I'm trying to make something like the image linked below:

图表示例

I already setup everything that I need to build it, it is just that damn grid line left.

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.

eg

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/

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
        }   
    }]
}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM