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

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

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

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

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

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

In Matplotlib, I make dashed grid lines as follows:

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

however, I can’t find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of adding the grid versus adding other elements makes no difference.

Is it possible to make it so that the grid lines appear behind everything else?


回答 0

据此-http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html-您可以使用Axis.set_axisbelow(True)

(我目前是第一次安装matplotlib,所以不知道这是否正确-我只是通过谷歌搜索“ matplotlib z顺序网格”找到它的-通常,“ z顺序”用于描述这种情况(z为轴“页面外”))

According to this – http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html – you can use Axis.set_axisbelow(True)

(I am currently installing matplotlib for the first time, so have no idea if that’s correct – I just found it by googling “matplotlib z order grid” – “z order” is typically used to describe this kind of thing (z being the axis “out of the page”))


回答 1

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

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

To me, it was unclear how to apply andrew cooke’s answer, so this is a complete solution based on that:

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

回答 2

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

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

要么

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

它适用于Matplotlib> = 2.0。

If you want to validate the setting for all figures, you may set

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

or

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

It works for Matplotlib>=2.0.


回答 3

我有同样的问题,以下工作:

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

提高3到一个更高的值,如果它不能正常工作。

I had the same problem and the following worked:

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

Increase 3to a higher value if it does not work.