Chart.js v2 - 隐藏网格线

Chart.js v2 - hiding grid lines

我正在使用 Chart.js v2 绘制一个简单的折线图。一切看起来都很好,除了有一些我不想要的网格线:

折线图的文档在这里:https://nnnick.github.io/Chart.js/docs-v2/#line-chart,但我找不到任何关于隐藏那些 "Grid Lines" 的信息。

如何去除网格线?

我找到了一个隐藏折线图中网格线的解决方案。

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

好的,没关系..我找到了窍门:

    scales: {
      yAxes: [
        {
          gridLines: {
                lineWidth: 0
            }
        }
      ]
    }

如果你想让它们默认消失,你可以设置:

Chart.defaults.scale.gridLines.display = false;
options: {
    scales: {
        xAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }],
        yAxes: [{
            gridLines: {
                drawOnChartArea: false
            }
        }]
    }
}

如果你想隐藏网格线但想显示y轴,你可以设置:

yAxes: [{...
         gridLines: {
                        drawBorder: true,
                        display: false
                    }
       }]

下面的代码仅从图表区域移除网格线而不是 x&y 轴标签中的网格线

Chart.defaults.scale.gridLines.drawOnChartArea = false;

请参考官方文档:

https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration

以下代码更改将隐藏网格线:

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

从版本 3.x 开始使用此语法。 请参阅 chart.js 迁移指南:https://www.chartjs.org/docs/latest/getting-started/v3-migration.html

scales: {
  x: {
    grid: {
      display: false
    }
  },
  y: {
    grid: {
      display: false
    }
  }
}

在 chartjs 3 中,访问此配置略有不同。 属性的名字不是gridLines,而是grid,正如官方文档中所示:

options.gridLines was renamed to options.grid

来源: https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#ticks

外观如下:

const options = {
  scales: {
    x: {
      grid: {
        display: false,
      },
    },
  },
};

ChartJS 3 更新:

  const options = {
    scales: {
      x: {
        grid: {
          display: false,
        },
      },

      y: {
        grid: {
          // display: false,
          color: 'rgba(217,143,7,0.1)',
        },
      },
    },
}