4

I have the following code to produce a arrow using 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)

enter image description here

Here, I just want to shift the arrows up/down or left/right afterwards. Is there any way to access "the coordinates" to make the shifting possible via the returned at.

I have tried at.set_x() and at.set_y(), but both only change one end of the arrow. Updating the position of annotation arrows afterwards is the key here.

Jiadong
  • 1,822
  • 1
  • 17
  • 37
  • It doesn’t have to be dynamic plots.. I have many situations where I have to update arrows. I only simplify the question here. – Jiadong Mar 31 '21 at 09:07
  • @akocz are you sure these functions exist? ... – Jiadong Mar 31 '21 at 14:24
  • Does this answer your question? [matplotlib: how to annotate point on a scatter automatically placed arrow?](https://stackoverflow.com/questions/9074996/matplotlib-how-to-annotate-point-on-a-scatter-automatically-placed-arrow) – akocz Mar 31 '21 at 14:50
  • 1
    You might also be interested in [mplcursors](https://mplcursors.readthedocs.io/) which offers a dynamic annotation while hovering around. Did you try `annotate(..., textcoords='offset points')` so the text keeps the same offset versus the data point when moving that point around? – JohanC Mar 31 '21 at 16:50
  • @JohanC I used that method before. – Jiadong Apr 01 '21 at 00:12
  • @akocz, I dont think that question is related to this one. What I need is "updating" programmatically. – Jiadong Apr 01 '21 at 04:25
  • Check out the answer https://stackoverflow.com/a/44828874/14393689 – akocz Apr 02 '21 at 08:51

1 Answers1

0

Unfortunately, both at.set_position() and at.set_x() / at.set_y() change the text position. However, you can change the xy-coordinates directly:

at.xy = (new_x,new_y)
mululu
  • 411
  • 2
  • 15