matplotlib添加矩形到图不到轴

Cob*_*bry 12 matplotlib python-2.7

我需要在matplotlib图上添加一个半透明的皮肤.我正在考虑在图中添加一个矩形,其中alpha <1且zorder足够高,因此它绘制在所有内容之上.

我在想这样的事情

figure.add_patch(Rectangle((0,0),1,1, alpha=0.5, zorder=1000))
Run Code Online (Sandbox Code Playgroud)

但我猜矩形只由Axes处理.有转弯吗?

Luc*_*asB 18

谷歌的其他人的迟到答案.

实际上有一种简单的方法,没有幻影轴,接近你原来的愿望.该Figure对象具有一个patches属性,您可以向其添加矩形:

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)])
Run Code Online (Sandbox Code Playgroud)

给出以下图片(我使用的是非默认主题):

绘图与矩形附加到图

transform参数使它使用图形级坐标,我认为这是你想要的.

  • 对我来说也很好用,但如果你正在使用 ``figure(constrained_layout=True)`` 确保在绘制数据之后和创建补丁之前调用 ``fig.execute_constrained_layout()`` 。 (2认同)

Alv*_*tes 6

您可以在图形顶部使用幻像轴,并根据需要更改修补程序,请尝试以下示例:

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()
Run Code Online (Sandbox Code Playgroud)