【发布时间】:2021-10-15 19:19:47
【问题描述】:
在这个动画情节的顶部,related to a previous project,为了使其更形象化,我希望值显示在点的顶部,但仅适用于最后一个数据,随着动画的进行。
下面的代码显示了所有的注释,因为动画添加了数据,所以最后一团糟……谁能帮我解决这个问题?
我尝试在注释的执行下方添加plt.pause() 和remove(),但结果发现注释总是在数据点之前......我不知道为什么......
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()
【问题讨论】:
-
您的意思是在每个循环中删除除最后一个点之外的所有点,还是我误解了?
-
@flyinthelotion 您好,感谢您的快速回复。由于它是在图形上动态显示数据的动画,所以我想要的是,每次图形更新时显示最后一个值。所以这将与 Veritasium 的视频 link 完全一样,他不仅动态绘制图形,还同时显示最后的值
-
我添加了我的更新答案,我第一次误解了
标签: python matplotlib animation plot data-visualization