python - 通过艺术家更新 matplotlib 中的文本

标签 python matplotlib

我希望能够自由更改 matplotlib 图。我通过查找 Artist 来做到这一点绘图中的对象(负责绘制所有内容)但我无法更新文本。
例如,在这里我尝试更改幅度文本。我可以更新颜色和位置,但不能像我想要的那样更新文本。
enter image description here

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')
manual sci notation label

要以编程方式获取文本坐标,似乎需要一些奇怪的解决方法。
理论上我们应该可以使用 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/

    相关文章:

    python 2 : calculate using user defined/named variables

    python matplotlib非法指令

    python - 将像素矩阵转换为图像python

    numpy - 安装错误 : ftheader. h:没有那个文件或目录

    python - 图中的箭头 matplotlib.pyplot

    python - WCS 作为使用 astropy 加载的数据立方体切片的 matplotlib 投影?

    python - 提前停止 Tensorflow 对象检测 API

    python - 如何加速代码?

    python - 将 GeoPandas 多多边形数据框扩展为每行一个多边形

    python - 为什么 Flask SQL Alchemy 允许保存 None 主键?