在 Matplotlib 中,我制作了如下的虚线网格线:
fig = pylab.figure()
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')
但是,我不知道如何(或者即使有可能)将网格线绘制在其他图形元素(例如条形图)后面。更改添加网格的顺序与添加其他元素没有区别。
是否有可能使网格线出现在其他所有内容的后面?
在 Matplotlib 中,我制作了如下的虚线网格线:
fig = pylab.figure()
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')
但是,我不知道如何(或者即使有可能)将网格线绘制在其他图形元素(例如条形图)后面。更改添加网格的顺序与添加其他元素没有区别。
是否有可能使网格线出现在其他所有内容的后面?
根据这个 - http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html - 你可以使用Axis.set_axisbelow(True)
(我目前是第一次安装 matplotlib,所以不知道这是否正确 - 我只是通过谷歌搜索“matplotlib z order grid”找到它 - “z order”通常用于描述这种事情(z 是轴“页外”))
对我来说,不清楚如何应用安德鲁库克的答案,所以这是一个基于此的完整解决方案:
ax.set_axisbelow(True)
ax.yaxis.grid(color='gray', linestyle='dashed')
如果要验证所有数字的设置,您可以设置
plt.rc('axes', axisbelow=True)
或者
plt.rcParams['axes.axisbelow'] = True
它适用于 Matplotlib>=2.0。
我有同样的问题,以下工作:
[line.set_zorder(3) for line in ax.lines]
fig.show() # to update
如果它不起作用3
,则增加到更高的值。
您可以尝试使用 Seaborn 的一种样式。例如:
import seaborn as sns
sns.set_style("whitegrid")
不仅网格线会落后,而且外观会更好。
您还可以将zorder
kwarg设置为matplotlib.pyplot.grid
plt.grid(which='major', axis='y', zorder=-1.0)
对于一些人(比如我)来说,只在“一些”其他元素后面绘制网格可能会很有趣。对于绘制顺序的精细控制,您可以直接在轴上使用matplotlib.artist.Artist.set_zorder :
ax.yaxis.grid(color='gray', linestyle='dashed')
ax.set_zorder(3)
这在matplotlib.axes.Axes.grid的注释中有所提及。