我正在使用 Chart.js v2 绘制一个简单的折线图。一切看起来都很好,除了有我不想要的网格线:
折线图的文档在这里:https://nnnick.github.io/Chart.js/docs-v2/#line-chart,但我找不到任何关于隐藏这些“网格线”的信息。
如何去除网格线?
我找到了一个可以隐藏折线图中网格线的解决方案。
将
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
}
}]
}
}
从 3.x 版本开始,使用此语法。 请参阅 Chart.js 迁移指南:https://www.chartjs.org/docs/latest/getting-started/v3-migration.html
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: false
}
}
}
options: {
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: false
}
}],
yAxes: [{
gridLines: {
drawOnChartArea: false
}
}]
}
}
如果您希望它们默认消失,您可以设置:
Chart.defaults.scale.gridLines.display = false;
如果想隐藏网格线但想显示y轴,可以设置:
yAxes: [{...
gridLines: {
drawBorder: true,
display: false
}
}]
下面的代码仅从图表区域中删除网格线,而不是 x&y 轴标签中的网格线
Chart.defaults.scale.gridLines.drawOnChartArea = false;
好吧,没关系..我找到了窍门:
scales: {
yAxes: [
{
gridLines: {
lineWidth: 0
}
}
]
}
在 ChartJS 3 中,访问此配置有一点不同。该属性的名称不是
gridLines
,而是grid
,正如官方文档所示:
更名为options.gridLines
options.grid
来源: https://www.chartjs.org/docs/latest/getting-started/v3-migration.html#ticks
它的外观如下:
const options = {
scales: {
x: {
grid: {
display: false,
},
},
},
};
请参考官方文档:
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration
下面的代码更改将隐藏网格线:
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}]
}
ChartJS 3 的更新:
const options = {
scales: {
x: {
grid: {
display: false,
},
},
y: {
grid: {
// display: false,
color: 'rgba(217,143,7,0.1)',
},
},
},
}
更新了 ChartJs 的代码,版本 = 4.3.0
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('myChart');
new Chart(ctx, {
type: 'line',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true,
grid:{
display:false
}
}
}
}
});
</script>
这在我的反应项目中为我做到了
scales: {
xAxis:{
grid: {
display: false
}
}
}
我希望这有帮助
我正在使用“react-chartjs-2”:“^5.2.0”,下面的代码为我解决了这个问题
},[![enter image description here][1]][1]