【问题标题】:matplotlib add rectangle to Figure not to Axesmatplotlib 将矩形添加到图而不是轴
【发布时间】:2021-08-18 22:49:29
【问题描述】:

我需要在我的 matplotlib 图上添加一个半透明的皮肤。我正在考虑为图形添加一个 alpha

我正在考虑类似的事情

figure.add_patch(Rectangle((0,0),1,1, alpha=0.5, zorder=1000))

但我猜矩形仅由 Axes 处理。有转机吗?

【问题讨论】:

  • 为什么你想这样做?
  • @tacaswell 在多个子图周围显示一个包含框架。

标签: python matplotlib


【解决方案1】:

谷歌搜索的其他人迟到的答案。

其实有一个简单的方法,没有幻影斧,接近你的初衷。 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)])

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

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

【讨论】:

  • 即使在使用 matplotlib 3.0.0 和 Python 3.6 时,它也很有效!
  • 对我也很有效,但如果您使用的是figure(constrained_layout=True),请确保在绘制数据之后和创建补丁之前调用fig.execute_constrained_layout()。
【解决方案2】:

您可以在图形顶部使用 幻影 轴并将补丁更改为您喜欢的样子,试试这个例子:

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

【讨论】:

  • 为了更好地使用tight_layout 之类的东西,请通过使用ax.twinx() 克隆现有的幻象轴来创建幻象轴。
【解决方案3】:

如果您不使用子图,使用gca() 会很容易。

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

【讨论】:

    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2020-03-16
    • 2016-11-29
    相关资源
    最近更新 更多