Matplotlib:在其他图形元素后面绘制网格线

199
在Matplotlib中,我使用以下方式创建虚线网格线:
fig = pylab.figure()    
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')

然而,我无法找到方法(甚至不确定是否可能)使得网格线绘制在其他图形元素之后,例如条形图。更改添加网格与添加其他元素的顺序没有任何区别。

是否有可能使网格线出现在其他所有内容后面?


18
ax.set_axisbelow(True) 仍然有效。对于 PDF 输出也很好用... - BandGap
12
我本来期望ax.set_axisbelow(True)是默认设置... - PatrickT
9个回答

195

有没有可能在保留顶部标签的同时,在条形/折线下面有网格线?我也单独发布了这个问题:https://dev59.com/_onca4cB1Zd3GeqP_35G - joelostblom
可能是这个 http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html,虽然这是一个古老的帖子。 - Jacques Kvam

148

对我来说,不清楚如何应用andrew cooke的答案,因此这是基于他的答案的完整解决方案:

ax.set_axisbelow(True)
ax.yaxis.grid(color='gray', linestyle='dashed')

1
非常好,运行得很顺畅,在这里! - Lucas Brito
3
截至2023年6月,这是我唯一有效的答案。将网格的zorder设置为0甚至负值,而将绘图元素的zorder设置得很高并没有起作用。 - Darren

77

如果您想验证所有图形的设置,可以设置

plt.rc('axes', axisbelow=True)
plt.rcParams['axes.axisbelow'] = True

这适用于Matplotlib>=2.0。


3
最佳答案,因为人们可能希望在所有图表中保持一致。 - Constantin
4
请确保在 plt.rc('axes', axisbelow=True) 之后放置 plt.grid()(或修改后的代码)。 - ConZZito

8

我有同样的问题,以下方法解决了:

[line.set_zorder(3) for line in ax.lines]
fig.show() # to update

如果不起作用,请将3增加到更高的值。


7
您还可以在 matplotlib.pyplot.grid 中设置 zorder 参数。
plt.grid(which='major', axis='y', zorder=-1.0)

1
对我没用 - Homero Esmeraldo
4
@HomeroEsmeraldo,你需要在所有被绘制的元素上设置 zorder 值。请注意不改变原意,使翻译易于理解。 - Francis Laclé

2
只需确保点的zorder值高于网格线,例如:
plt.scatter(x,y,c="k",marker="x",zorder=2)

跟随着
plt.grid(linestyle="--",alpha=0.5,zorder=1)

1
您可以尝试使用Seaborn的样式之一。例如:
import seaborn as sns  
sns.set_style("whitegrid")

网格线不仅会被隐藏,而且外观更加美观。

1

对于一些人(比如我),仅在“某些”其他元素的后面绘制网格可能是有趣的。为了精细控制绘制顺序,您可以直接在轴上使用matplotlib.artist.Artist.set_zorder

ax.yaxis.grid(color='gray', linestyle='dashed')
ax.set_zorder(3)

这在关于 matplotlib.axes.Axes.grid 的注释中有提到。

0
这些答案对我不起作用(zorderaxisbelowset_zorder):
fig, ax = plt.subplots(3, 1, dpi=200)
ax[0].yaxis.grid(True, which='major', linestyle='--')
ax[0].boxplot(data, positions=[0, 0.5], widths=[0.5, 0.5])

改用patch_artist来改变图形元素的背景颜色,这对我起了作用。
l = ax[0].boxplot(data, positions=[0, 0.5], widths=[0.5, 0.5],
  patch_artist=True)
for bplot in (l,):
  for patch, color in zip(bplot['boxes'], ['white', 'white']):
    patch.set_facecolor(color)
``

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接