隐藏yaxis时如何在matplotlib中绘制水平网格

How draw horizontal grid in matplotlib when hidden yaxis

出于可视化原因,我删除了 yaxis 标签,但我想保留水平网格。我该怎么做?

ax = plt.gca()
ax.set_ylim([0,23])
ax.axes.xaxis.set_visible(False)
ax.yaxis.grid()

不确定您是想只删除标签还是同时删除刻度线。

无论如何,行

ax.axes.yaxis.set_visible(False) #I am assuming it is y not x

可以删除。我们没有隐藏轴,只是隐藏了刻度标签。

为此,添加:

from matplotlib.ticker import NullFormatter
ax.yaxis.set_major_formatter(NullFormatter())

这给出:

如果你也想去掉勾marks/lines,你可以进一步添加:

ax.yaxis.set_tick_params(left=False)

所以:

import matplotlib.pyplot as plt
from matplotlib.ticker import NullFormatter

fig = plt.figure()
ax = fig.add_subplot()
ax.set_ylim([0,23])
ax.yaxis.set_major_formatter(NullFormatter()) # to remove the labels
ax.yaxis.set_tick_params(left=False) # to remove the tick marks
ax.yaxis.grid()
plt.show()