使垂直网格线显示在matplotlib的线图中

2024-03-29 07:13:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的绘图上同时得到水平和垂直网格线,但默认情况下只有水平网格线出现。我使用python中的sql查询中的pandas.DataFrame生成一个x轴上有日期的线图。我不知道为什么他们没有出现在日期上,我试图寻找一个答案,但找不到。

我只使用下面的简单代码来绘制图表。

data.plot()
grid('on')

data是包含日期和来自sql查询的数据的DataFrame。

我也试过添加下面的代码,但仍然得到相同的输出,没有垂直网格线。

ax = plt.axes()        
ax.yaxis.grid() # horizontal lines
ax.xaxis.grid() # vertical lines

有什么建议吗?

enter image description here


Tags: 答案代码绘图dataframepandassqldata水平
3条回答

您可能需要在调用中给出布尔参数,例如使用ax.yaxis.grid(True),而不是ax.yaxis.grid()。另外,由于您同时使用这两个维度,因此可以组合成ax.grid,这对这两个维度都有效,而不是对每个维度执行一次。

ax = plt.gca()
ax.grid(True)

这应该能解决你的问题。

According to matplotlib documentationAxesgrid()方法的签名如下:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

因此,为了显示x轴和y轴的网格线,我们可以使用以下代码:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

此方法使我们能够更好地控制网格线的显示内容。

plt.gca().xaxis.grid(True)证明是我的解决方案

相关问题 更多 >