我希望能够自由更改 matplotlib 图。我通过查找 Artist
来做到这一点绘图中的对象(负责绘制所有内容)但我无法更新文本。
例如,在这里我尝试更改幅度文本。我可以更新颜色和位置,但不能像我想要的那样更新文本。
import matplotlib.pyplot as plt
# Make the plot
data = [1e6 + i for i in range(10)]
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(data)
plt.title("Normal")
plt.subplot(1, 2, 2)
plt.plot(data)
plt.title("Updated Artist")
plt.draw()
# Find all `Text` Artist objects in the current axis
t = plt.gca().findobj(plt.Text)
# Filter them to get the one with the text we want
t = next(filter(lambda x: x.get_text() == '+1e6', t))
# Update the position
pos = t.get_position()
pos = (pos[0]+0.1, pos[1])
t.set_position(pos)
# Set properties
t.set_text('1,000,000') # This doesn't work! :(
t.set_color('red')
plt.show()
最佳答案
我不确定这是有意为之还是长期存在的错误,但是 set_text()
对 offsetText
不起作用至少 since 2015 .
您可以隐藏 offsetText
然后添加您的自定义标签 Axes.text
:
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
ax1.plot(data)
ax1.set_title('Normal')
ax2.plot(data)
ax2.set_title('Updated Artist')
ax2.yaxis.offsetText.set_visible(False)
ax2.text(-0.4, max(data)+0.6, '1,000,000', color='r', size='small')
要以编程方式获取文本坐标,似乎需要一些奇怪的解决方法。
理论上我们应该可以使用
get_position()
与 get_transform()
,但这总是将文本放在 (0, 0.5)
:# does not work
x, y = ax2.yaxis.offsetText.get_position()
transform = ax2.yaxis.offsetText.get_transform()
ax2.text(x, y, '1,000,000', transform=transform)
如果我们首先强制 Canvas 重绘,它会将文本放置在 (0, 345.952885)
这是更接近但仍然不正确的:# still does not work
plt.draw()
x, y = ax2.yaxis.offsetText.get_position()
transform = ax2.yaxis.offsetText.get_transform()
ax2.text(x, y, '1,000,000', transform=transform)
所以我能让这个工作的唯一方法是:ax2.yaxis.offsetText.get_position()
# (0, 301.55984375)
ax2.text(0, 301.55984375, '1,000,000', transform=ax2.yaxis.offsetText.get_transform())
关于python - 通过艺术家更新 matplotlib 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68881200/