Oblomov
Oblomov

Reputation: 9635

plot differently colored background rectangles on plot over several axes

The following code is a snippet from a much larger function that plots several financial indicators over 3 axis:

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

The final plot looks like that:

enter image description here

Now I want to add background rectangles with a height that covers the complete x-axis (i.e. over all axis) and a width of several minutes, like that:

enter image description here

How can I do that?

Upvotes: 2

Views: 2102

Answers (2)

MMF
MMF

Reputation: 5931

This works :

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

Upvotes: 5

JMat
JMat

Reputation: 737

You can use the patches from 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

Upvotes: 2

Related Questions