首页 > 解决方案 > 用补丁剪裁轴

问题描述

我在理解如何用补丁剪辑轴时遇到了一些麻烦。我想让蓝色矩形位于轴的背景中。但我的剪辑电话什么也没做。

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

在此处输入图像描述

我需要如何正确设置它?文档非常缺乏。

标签: pythonmatplotlibclipping

解决方案


您需要做的就是提供zorder将其放入后台。具体来说,zorder=0在本例中为您的Rectangle补丁。

可以将zorder其视为决定堆叠在什么之上的参数。zorder=0只会发送堆栈中最低的补丁,这意味着情节的最后一层。

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)

在此处输入图像描述


推荐阅读