【问题标题】:How to Label patch in matplotlib如何在 matplotlib 中标记补丁
【发布时间】:2015-09-25 15:31:40
【问题描述】:

我在 matplotlib 中以交互模式绘制矩形补丁。我想为每个补丁添加文本。我不想注释它们,因为它会降低速度。我正在使用补丁的“标签”属性,但它不起作用。 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()

【问题讨论】:

  • 如果要显示标签,需要调用plt.legend()
  • 您可能想look at this example from the docs 它向您展示了如何在补丁中的各个点添加文本。如果您真的想在图例中显示所有现有标签 - 请参阅 plt.legend()
  • 补丁是任意的 Artist 对象,所以 plt.legend() 不是你想要的。如果要在对象上显示可见文本,请使用 plt.text()plt.annotate()。在 matplotlib 中,label 不是一个可见的文本标签,它是一个内部“句柄”,用于查找具有 plt.findobj() 的子类 Artist 的对象,但这似乎不适用于补丁。

标签: python matplotlib plot label patch


【解决方案1】:

你已经知道补丁在哪里,所以你可以计算出中心在哪里并在那里添加一些文本:

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 的建议是实现这一目标的正确方法

【讨论】:

  • annotate 为这类事情提供了更强大的 API。
  • 您通常会指定horizontalalignment="center"(或更简洁的ha="center")来使文本居中而不是微调坐标。
  • 我显然应该知道...相应地承认!
  • @areuexperienced,感谢您的回答。我正在绘制来自传感器的数据,因此绘图处于无限循环中。如果我添加文本/注释对象,它会降低速度。我想使用补丁的标签属性,就像在这个链接中解释的那样,但我无法理解。 matplotlib.org/examples/shapes_and_collections/…
  • @Luqman ,在您发布的示例中,label 只是一个调用plt.text 的函数,所以它与我展示的相同。不同的是 label 参数传递给您正在制作的补丁,这与 plt.legend 有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2020-10-07
  • 2017-01-06
  • 1970-01-01
  • 2018-04-24
  • 2014-03-08
  • 2011-06-03
相关资源
最近更新 更多