Cobry
Cobry

Reputation: 4548

matplotlib add rectangle to Figure not to Axes

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 ?

Upvotes: 28

Views: 20948

Answers (3)

AGS
AGS

Reputation: 14498

If you aren't using subplots, using gca() will work easily.

from matplotlib.patches import Rectangle
fig = plt.figure(figsize=(12,8))
plt.plot([0,100],[0,100])
plt.gca().add_patch(Rectangle((25,50),15,15,fill=True, color='g', alpha=0.5, zorder=100, figure=fig))

enter image description here

Upvotes: 3

LucasB
LucasB

Reputation: 3573

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.

Upvotes: 40

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17485

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()

Upvotes: 9

Related Questions