Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib add rectangle to Figure not to Axes

Tags:

I need to add a semi transparent skin over my matplotlib figure. I was thinking about adding a rectangle to the figure with alpha <1 and a zorder high enough so its drawn on top of everything.

I was thinking about something like that

figure.add_patch(Rectangle((0,0),1,1, alpha=0.5, zorder=1000))

But I guess rectangles are handled by Axes only. is there any turn around ?

like image 625
Cobry Avatar asked Feb 03 '14 18:02

Cobry


2 Answers

Late answer for others who google this.

There actually is a simple way, without phantom axes, close to your original wish. The Figure object has a patches attribute, to which you can add the rectangle:

fig, ax = plt.subplots(nrows=1, ncols=1)
ax.plot(np.cumsum(np.random.randn(100)))
fig.patches.extend([plt.Rectangle((0.25,0.5),0.25,0.25,
                                  fill=True, color='g', alpha=0.5, zorder=1000,
                                  transform=fig.transFigure, figure=fig)])

Gives the following picture (I'm using a non-default theme):

Plot with rectangle attached to figure

The transform argument makes it use figure-level coordinates, which I think is what you want.

like image 200
LucasB Avatar answered Oct 19 '22 02:10

LucasB


You can use a phantom axes on top of your figure and change the patch to look as you like, try this example:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
ax.set_zorder(1000)
ax.patch.set_alpha(0.5)
ax.patch.set_color('r')

ax2 = fig.add_subplot(111)
ax2.plot(range(10), range(10))

plt.show()
like image 26
Alvaro Fuentes Avatar answered Oct 19 '22 01:10

Alvaro Fuentes