在多个轴上的绘图上绘制不同颜色的背景矩形

时间:2016-10-04 16:13:17

标签: python matplotlib

以下代码是一个更大功能的片段,它绘制了3个轴上的几个财务指标:

left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6'  # the axes background color
ax1 = fig.add_axes(rect1)#, axisbg=axescolor)  # left, bottom, width, height
ax2 = fig.add_axes(rect2,sharex=ax1)#, axisbg=axescolor)
ax3 = fig.add_axes(rect3,sharex=ax1)#, axisbg=axescolor

最终情节如下:

enter image description here

现在我要添加背景矩形,其高度覆盖整个x轴(即在所有轴上),宽度为几分钟,如下所示:

enter image description here

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用patches

中的matplotlib
import matplotlib.patches as patches

left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]
fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6'  # the axes background color
ax1 = fig.add_axes(rect1)#, axisbg=axescolor)  # left, bottom, width, height
ax2 = fig.add_axes(rect2,sharex=ax1)#, axisbg=axescolor)
ax3 = fig.add_axes(rect3,sharex=ax1)#, axisbg=axescolor
ax1.add_patch(patches.Rectangle(
        (0.1, 0.1),   # (x,y)
        0.5,          # width
        0.5,          # height
        alpha = 0.5)) #transparency

答案 1 :(得分:1)

这有效:

ax1.axvspan(start, end, facecolor='g', alpha=0.25, label=my_label)