On top of this animation plot, related to a previous project, to make it more presentable, I want the value to be displayed on top of the point, but ONLY for the last data, as the animation goes along.
Below the code is showing all of the annotations, as the animation adding the data in, thus it's mess in the end...Can anyone help me on resolving this issue?
I tried to add the plt.pause()
and remove()
underneath the execution of annotation, but then it turns out the annotation always precede the data point....I have no idea why....
import numpy as np
from matplotlib.animation import FuncAnimation
from matplotlib import pyplot as plt
def collatz(k):
seq = [k]
while seq[-1] > 1:
if k % 2 == 0:
seq.append(k/2)
else:
seq.append(3*k+1)
k = seq[-1]
return seq
y= collatz(22)
x = list(range(len(y)))
fig = plt.figure()
plt.xlim(1,len(y))
plt.ylim(1,max(y))
draw, = plt.plot([],[], marker='o', markersize='4', color='magenta')
def update(idx):
draw.set_data(x[:idx], y[:idx])
plt.gca()
ann = plt.annotate(f'{y[idx]:.1f}', (x[idx],y[idx]), textcoords="offset points", xytext=(0,0.5), ha="center")
#plt.pause(0.5)
#ann.remove()
return draw,
a = FuncAnimation(fig, update, frames=len(x), interval=30, repeat=False)
plt.show()