ChartJ中X轴上的特定网格线

lvmkulzt  于 2022-11-23  发布在  Chart.js
关注(0)|答案(3)|浏览(425)

有没有办法在特定的X轴值上放置一条网格线?
我试图让一些像下面链接的图像:

我已经设置了所有我需要建立它,它只是那该死的网格线离开。

wvt8vs2t

wvt8vs2t1#

当然,您只需要在xAxes上创建一个自定义回调函数,并为要过滤掉的所有网格线返回null,从而在图表中只留下所需的一条网格线。
例如:

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

工作示例:https://jsfiddle.net/fraser/kuwh3nzs/

aemubtdh

aemubtdh2#

网格中的color属性支持JS函数,然后使用context,您可以为不同的网格线给予不同的颜色。https://www.chartjs.org/docs/latest/samples/scale-options/grid.html

bis0qfac

bis0qfac3#

我找到了一个可以隐藏折线图中网格线的解决方案。
将gridLines颜色设置为与div的背景颜色相同。

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

}
或使用

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

相关问题