最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Specific grid line in X axis in ChartJs - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Mar 31, 2020 at 10:42 Fraser 17.1k8 gold badges57 silver badges110 bronze badges asked Mar 30, 2020 at 19:35 João Luiz ArandaJoão Luiz Aranda 231 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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/fraser/kuwh3nzs/

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/docs/latest/samples/scale-options/grid.html

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
        }   
    }]
}
}
发布评论

评论列表(0)

  1. 暂无评论