matplotlib - 如何为图形背景添加斑马条纹?
我正在用matplotlib制作一个简单的折线图,我想给图表的背景加上斑马条纹,也就是让每一行的颜色交替不同。请问有什么方法可以做到这一点吗?
我的图表已经有了网格线,并且只有主要的刻度。
编辑:下面是我评论中的代码,不过更容易看懂:
yTicks = ax.get_yticks()[:-1]
xTicks = ax.get_xticks()
ax.barh(yTicks, [max(xTicks)-min(xTicks)] * len(yTicks),
height=(yTicks[1]-yTicks[0]), left=min(xTicks), color=['w','#F0FFFF'])
1 个回答
5
这里有个简单的小技巧,利用条形图(axes.barh)来模拟条纹效果。
import matplotlib.pyplot as plt
# initial plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3,4,5])
yTickPos,_ = plt.yticks()
yTickPos = yTickPos[:-1] #slice off the last as it is the top of the plot
# create bars at yTickPos that are the length of our greatest xtick and have a height equal to our tick spacing
ax.barh(yTickPos, [max(plt.xticks()[0])] * len(yTickPos), height=(yTickPos[1]-yTickPos[0]), color=['g','w'])
plt.show()
效果如下: