简体   繁体   English

ChartJs 中 X 轴的特定网格线

[英]Specific grid line in X axis in ChartJs

Is there a way to place a single grid line at specific XAxis value?有没有办法将单个网格线放置在特定的 XAxis 值处?

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.当然,您只需要在xAxes上创建一个自定义回调,并为要过滤掉的所有网格线返回null - 在图表中留下您需要的单个网格线。

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/工作示例: 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.将 gridLines 颜色设置为与 div 的背景颜色相同。

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.网格中的color属性具有支持的 JS 函数,然后使用context可以为不同的网格线提供不同的 colors。 https://www.chartjs.org/docs/latest/samples/scale-options/grid.html https://www.chartjs.org/docs/latest/samples/scale-options/grid.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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