我正在以交互方式在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()
最佳答案
您已经知道补丁的位置,因此您可以计算中心位置,并在其中添加一些文本:
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()
plt.text
的坐标确定了文本的开始位置,因此您可以在x方向上微调一下,以使文本更加居中,例如centerx - 0.05
。显然,@ JoeKington的建议是实现此目标的正确方法
关于python - 如何在matplotlib中标记补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32785705/