Matplotlib:在其他图形元素后绘制网格线
在Matplotlib这个绘图库中,我是这样画虚线网格线的:
fig = pylab.figure()
ax = fig.add_subplot(1,1,1)
ax.yaxis.grid(color='gray', linestyle='dashed')
但是,我找不到方法(或者说不确定是否可以)让网格线画在其他图形元素的后面,比如柱状图。无论我先加网格线还是先加其他元素,顺序改变都没有效果。
有没有办法让网格线在所有其他元素的后面显示呢?
10 个回答
79
如果你想检查所有图形的设置,可以这样设置:
plt.rc('axes', axisbelow=True)
或者
plt.rcParams['axes.axisbelow'] = True
这个方法适用于Matplotlib版本2.0及以上。
153
对我来说,如何使用Andrew Cooke的回答并不清楚,所以这是基于他的回答的一个完整解决方案:
ax.set_axisbelow(True)
ax.yaxis.grid(color='gray', linestyle='dashed')
197
根据这个链接 - http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html - 你可以使用 Axis.set_axisbelow(True)
这个命令。
(我现在第一次安装matplotlib,所以不确定这个说法是否正确 - 我只是通过搜索“matplotlib z order grid”找到的这个信息 - “z order”通常用来描述这种情况(z轴是指“从页面外出来”的轴))