Matplotlib add rectangle to shape not to axes

I need to add translucent skin on top of the matplotlib shape. I was thinking of adding a rectangle to the shape with alpha <1 and zorder high enough to be 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 think that rectangles are processed only by Axes. is there any twist

+7
matplotlib
source share
2 answers

You can use the phantom axes on top of your figure and change the patch to look the way 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() 
+4
source share

Late answer for others who do this.

Actually there is a simple way, without phantom axes, next to your original desire. The Figure object has a patches attribute to which you can add a 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 image (I am using a theme other than the default theme):

Plot with a rectangle attached to the drawing

The transform argument allows you to use the coordinates at the shape level that I think you want.

+4
source share

All Articles