如何在matplotlib中标记补丁

问题描述 投票:5回答:1

我正在以交互方式在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()
matplotlib label patch
1个回答
7
投票

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

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

centeredtext

plt.text的坐标确定了文本的开始位置,所以您可以在x方向上微调一下,以使文本更加居中,例如centerx - 0.05 显然@JoeKington的建议是实现此目标的正确方法

© www.soinside.com 2019 - 2024. All rights reserved.