28

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 ?

3
  • 2
    why do you want to do this? Commented Feb 3, 2014 at 21:19
  • 1
    @tacaswell to Show an encompassing Frame around multiple subplots. Commented Sep 28, 2016 at 7:37
  • 1
    fig.add_artist(patch) matplotlib.org/stable/api/_as_gen/… can add a patch Commented Apr 8 at 14:40

3 Answers 3

40

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This works like a charm even with matplotlib 3.0.0 and Python 3.6!
Works great for me too, but if you're using figure(constrained_layout=True) make sure to call fig.execute_constrained_layout() after plotting the data and before creating the patch.
Good call. Or fig.get_layout_engine().execute() in newer matplotlib versions.
9

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

1 Comment

To make this work better with things like tight_layout, create the phantom axes by cloning an existing one with ax.twinx().
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.