如何将 matplotlib 补丁定位在轴范围之外(以便它可以在标题、图例或图形的任何位置旁边) [英] How to position a matplotlib patch outside of the axes range (so that it could be next to the title, or legend, or anywhere on the figure)

查看:21
本文介绍了如何将 matplotlib 补丁定位在轴范围之外(以便它可以在标题、图例或图形的任何位置旁边)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

fig, ax = plt.subplots()
ax.scatter([1, 2, 3, 4, 5], [34, 22, 11, 4, 6], s=100)
_ = ax.text(x=0, y=1.1, s="This is some text", transform=ax.transAxes, fontsize=20)

rect = mpl.patches.Rectangle(
    (0.5, 0.5), width=0.05, height=0.05, color="red", transform=ax.transAxes,
)
ax.add_patch(rect)

哪个创建了

我想将补丁添加到以下位置:

I would like to add the patch to the following location:

使情节如下所示:

不过,我似乎无法在轴脊区域之外添加补丁,例如以下代码:

It seems that I am unable to have patches outside of the axes spines area though, for example the following code:

fig, ax = plt.subplots()
ax.scatter([1, 2, 3, 4, 5], [34, 22, 11, 4, 6], s=100)
_ = ax.text(x=0, y=1.1, s="This is some text", transform=ax.transAxes, fontsize=20)

rect = mpl.patches.Rectangle(
    (0.5, 0.5), width=0.05, height=0.5, color="red", transform=ax.transAxes,
)
ax.add_patch(rect)

给予

查看 matplotlib.figure.Figure 的方法,我看不到 add_patch

Looking in the method for matplotlib.figure.Figure I can't see anything for add_patch

['_clippath',
 '_path_effects',
 'get_clip_path',
 'get_path_effects',
 'get_transformed_clip_path_and_affine',
 'patch',
 'patches',
 'set_clip_path',
 'set_path_effects']

上面是其中带有 pat 的方法.

The above are the methods with pat in them.

推荐答案

您可以通过设置 clip_on = False 来禁用剪切,然后将修补程序放置在所需的位置.例如:

You can disable clipping by setting clip_on=False, and then you can position the patch where you want. For example:

import matplotlib as mpl
from matplotlib import pyplot as plt

fig, ax = plt.subplots()
ax.scatter([1, 2, 3, 4, 5], [34, 22, 11, 4, 6], s=100)
_ = ax.text(x=0, y=1.1, s="This is some text", transform=ax.transAxes, fontsize=20)

rect = mpl.patches.Rectangle(
    (0.5, 1.1), width=0.05, height=0.05, color="red", transform=ax.transAxes,
    clip_on=False
)

ax.add_patch(rect)
plt.show()

赠予:

这篇关于如何将 matplotlib 补丁定位在轴范围之外(以便它可以在标题、图例或图形的任何位置旁边)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆