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

问题描述 投票:0回答:8

在 Matplotlib 中,我制作网格虚线如下:

fig = pylab.figure()    
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')

但是,我不知道如何(或者即使可能)使网格线绘制在其他图形元素(例如条形图)后面。更改添加网格的顺序与添加其他元素没有什么区别。

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

python matplotlib grid
8个回答
186
投票

根据此 - http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html - 你可以使用

Axis.set_axisbelow(True)

(我目前是第一次安装 matplotlib,所以不知道这是否正确 - 我只是通过谷歌搜索“matplotlib z order grid”找到它 - “z order”通常用于描述这种事情(z 是轴“超出页面”))


146
投票

对我来说,不清楚如何应用安德鲁·库克的答案,所以这是一个基于此的完整解决方案:

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

77
投票

如果您想验证所有数字的设置,您可以设置

plt.rc('axes', axisbelow=True)

plt.rcParams['axes.axisbelow'] = True

它适用于 Matplotlib>=2.0。


8
投票

我遇到了同样的问题,以下方法有效:

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

如果不起作用,请将

3
增加到更高的值。


7
投票

您还可以在

zorder
 中设置 
matplotlib.pyplot.grid

kwarg
plt.grid(which='major', axis='y', zorder=-1.0)

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
投票

只需确保点的 zorder 值高于网格线,例如:

plt.scatter(x,y,c="k",marker="x",zorder=2)
plt.grid(linestyle="--",alpha=0.5,zorder=1)

© www.soinside.com 2019 - 2024. All rights reserved.