问题描述
x = ['01-02', '02-02', '03-02', '04-02', '05-02']
y = [2, 2, 3, 7, 2]
fig, ax = plt.subplots(1, 1)
ax.bar(range(len(y)), y, width=0.3,align='center',color='skyblue')
plt.xticks(range(len(y)), x, size='small')
plt.savefig('/home/user/graphimages/foo2.png')
plt.close()
我想在条形图后面绘制(x和y的)网格线.
I want to draw grid lines (of x & y) behind the bar graph.
推荐答案
要添加网格,只需添加
ax.grid()
如果您希望网格位于条形图的后面,请添加
If you want the grid to be behind the bars then add
ax.grid(zorder=0)
ax.bar(range(len(y)), y, width=0.3, align='center', color='skyblue', zorder=3)
重要的是条形图的zorder
大于网格.实验似乎zorder=3
是实际上能提供所需效果的最低值.我不知道为什么zorder=1
还不够.
The important part is that the zorder
of the bars is greater than grid. Experimenting it seems zorder=3
is the lowest value that actually gives the desired effect. I have no idea why zorder=1
isn't sufficient.
编辑:我注意到这个问题已经在此处使用了答案不同的方法,尽管它遭受一些链接腐烂.据我所知,这两种方法都产生相同的结果,但是安德鲁·库克的答案更为优雅.
EDIT:I have noticed this question has already been answered here using a different method although it suffers some link rot. Both methods yield the same result as far as I can see but andrew cooke's answer is more elegant.
这篇关于如何在Matplotlib条形图后面绘制网格线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!