如何在matplotlib中标记补丁

Ton*_*ker 6 patch matplotlib

我正在以交互方式在matplotlib中绘制矩形补丁。我想向每个补丁添加文本。我不想注释它们,因为它会降低速度。我正在使用补丁的'label'属性,但无法正常工作。Ayone知道如何在补丁中添加1个字符串。

import matplotlib.pyplot as plt
import matplotlib.patches as patches

plt.ion()
plt.show()
x=y=0.1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
patch= ax1.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
    alpha=0.1,facecolor='red',label='Label'))

plt.pause(0)
plt.close()
Run Code Online (Sandbox Code Playgroud)

are*_*ced 6

您已经知道补丁的位置,因此可以计算出中心位置,并在其中添加一些文本:

import matplotlib.pyplot as plt
import matplotlib.patches as patches

x=y=0.1
fig1 = plt.figure()
ax1 = fig1.add_subplot(111, aspect='equal')
patch= ax1.add_patch(patches.Rectangle((x, y), 0.5, 0.5,
    alpha=0.1,facecolor='red',label='Label'))

centerx = centery = x + 0.5/2 # obviously use a different formula for different shapes

plt.text(centerx, centery,'lalala')
plt.show()
Run Code Online (Sandbox Code Playgroud)

居中文本

用于plt.text确定文本从何处开始的坐标,因此您可以在x方向上微移一下,以使文本更居中,例如centerx - 0.05。 显然,@ JoeKington的建议是实现此目标的正确方法

  • “注释”为这种事情提供了更强大的API。 (5认同)
  • 您通常会指定“horizo​​ntalalignment =“center””(或更简洁地,“ha =“center””)来使文本居中而不是微移坐标。 (2认同)
  • @Luqman,在您发布的示例中,“ label”只是一个调用“ plt.text”的函数,因此与我所显示的相同。传递给您正在制作的补丁的“ label”参数与“ plt.legend”有关,这是不同的。 (2认同)