【问题标题】:How to shift matplotlib annotations after creating them?创建 matplotlib 注释后如何移动它们?
【发布时间】:2021-06-27 04:49:25
【问题描述】:

我有以下代码使用ax.annotate() 生成箭头:

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = ax.plot(t, s, lw=2)

at = ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
        arrowprops=dict(facecolor='black', shrink=0.05),
        )
ax.set_ylim(-2, 2)

在这里,我只想在之后向上/向下或向左/向右移动箭头。有什么方法可以通过返回的at 访问“坐标”以使移动成为可能。

我试过at.set_x()at.set_y(),但都只改变了箭头的一端。 事后更新注释箭头的位置是这里的关键。

【问题讨论】:

  • 不一定是动态图。我有很多情况需要更新箭头。我这里只简化问题。
  • @akocz 你确定这些函数存在吗? ...
  • 您可能还对mplcursors 感兴趣,它在悬停时提供动态注释。您是否尝试过annotate(..., textcoords='offset points'),以便在移动该点时文本与数据点保持相同的偏移量?
  • @JohanC 我以前用过那个方法。

标签: python python-3.x matplotlib


【解决方案1】:

很遗憾,at.set_position()at.set_x() / at.set_y() 都会更改文本位置。但是,您可以直接更改 xy 坐标:

at.xy = (new_x,new_y)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-06
    • 2011-10-29
    • 2016-05-14
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2022-01-17
    相关资源
    最近更新 更多