Search code examples
pythonmatplotlibclipping

Clipping axes with patch


I have some trouble understanding how to clip an axes with a patch. I would like to have the blue rectangle be in the background of the axes. But my clipping call does nothing.

import matplotlib.pyplot as plt
from matplotlib import patches
import numpy as np

fig = plt.figure()

X, Y = np.mgrid[-1:1:.1, -1:1:.1]
Z = X+Y

ax1 = fig.add_subplot(111)
ax1.contourf(X, Y, Z)

frame = patches.Rectangle(
        (-.1,-.1), 1.2, 1.2, transform=ax1.transAxes, alpha=.5, fc='b', fill=True, linewidth=3, color='k'
    )
ax1.set_clip_path(frame) # has no effect
fig.patches.append(frame)

fig.show()

enter image description here

How do I need to set this up correctly? The documentation is very lacking.


Solution

  • All you need to do is to provide the zorder to put it into the background. Specifically, zorder=0 in the present case for your Rectangle patch.

    Think of zorder as the parameter which decides what is stacked on top of what. zorder=0 would simply send the patch lowest in the stack which means the back most layer of the plot.

    frame = patches.Rectangle(
            (-.1,-.1), 1.2, 1.2, transform=ax1.transAxes, alpha=.5, fc='b', fill=True, linewidth=3, color='k'
        , zorder=0) # <--- zorder specified here
    ax1.set_clip_path(frame) # has no effect
    fig.patches.append(frame)
    

    enter image description here