您好,亲爱的 StackOverfloooow 成员(member), 我无法理解 matplotlib 的 FuncAnimation 模块。你介意帮我一下吗?我有两个问题:
- 为什么 die
init
和animate
函数在仅返回PLOT
之后都需要一个逗号? - 为什么我的代码不更新
time_text
?如果我让它在每个动画之后打印 t,我会在控制台中正确地添加一个,但文本不会在绘图中更新。
.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
sub = fig.add_subplot(111,xlim=(0, 10), ylim=(0, 1))
PLOT, = sub.plot([],[])
time_text = sub.text(1,1,"",transform = sub.transAxes, ha="right")
t = 0
def init():
PLOT.set_data([],[])
time_text.set_text("")
return PLOT,time_text
def animate(i):
global t
x = np.linspace(0,10,1000)
y = np.exp(- ((x-0.01*i)/(2))**2 )/np.sqrt(2*np.pi)
t += 1
PLOT.set_data(x,y)
time_text.set_text("time = "+str(t))
return PLOT, time_text
ani = animation.FuncAnimation(fig, animate, init_func=init, frames=2000, interval=20, blit=True)
plt.show()
最佳答案
1) 不太确定你的意思。在 init
和 animate
中,你需要同时返回 PLOT
和 time_text
,所以你用逗号分隔它们每个函数都会返回一个元组。
对于 PLOT, = sub.plot([],[])
中的“悬挂”逗号,sub.plot
返回一个包含单个元素的列表,一个 matplotlib.lines.Line2D
对象。 PLOT,
正在解压缩这个单个元素列表。所以,你也可以这样做:
PLOT = sub.plot([],[])[0]
获取元素。
2) 您的代码确实更新了 time_text
,您只是将其绘制在图形的边界之外。例如更改:
time_text = sub.text(1,1,"",transform = sub.transAxes, ha="right")
收件人:
time_text = sub.text(1,0,"",transform = sub.transAxes, ha="right")
让它显示在右下角,或者 0.5, 0.5
让它显示在屏幕中间。
关于Python Matplotlib 函数动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083439/