如何在Matplotlib中设置函数的动画

2024-04-20 11:41:45 发布

您现在位置:Python中文网/ 问答频道 /正文

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation


#make the figure
# - set up figure, set up axis(xlim,ylim), set up line as tuple for 
animation
fig = plt.figure()
ax = plt.axes(xlim=(-10,50), ylim=(1,50))
line, = ax.plot([],[], lw=2)

#initialization function - display bkgd for each frame
#line has function set data, return it as a tuple
def init():
    line.set_data([],[])
    return line,

speed = 0.01

#animation function - this is where the physics goes
def animate(i): #i is animation frames
    x = np.linspace(0,2,100) #creates set of num evenly spaces from 0,2
    y = (x - speed * i)+(((x - speed * i)^2)/2)+(((x - speed * i)^3)/6)
    line.set_data(x,y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=100, 
interval=20, blit=True)

plt.show()

我试图用无穷级数的定义来近似“e^x”,并把它画在一个图上。在

不管出于什么原因,这段代码会生成一个带有绘图的对话框,该对话框的结尾是退出代码1。在

我不明白为什么这不起作用。在


Tags: importdatareturnmatplotlibinitasnpline
1条回答
网友
1楼 · 发布于 2024-04-20 11:41:45

计算y时出现了一个打字错误。Python中的求幂运算符是**,而不是{}。如果使用y = (x - speed * i)+(((x - speed * i) ** 2)/2)+(((x - speed * i) ** 3)/6),则原始问题中的代码将正常运行。在


奇怪的是你没有得到预期的回溯。例如,如果你尝试

x = np.ones(5)
x ^ 1

您将得到一个TypeError

^{pr2}$

似乎这个回溯在FuncAnimator中被抑制了。我浏览了一下source code,但没有什么东西跳到我身上引起压制。

进一步的研究表明,回溯的抑制可能是由PyCharm引起的,而不是matplotlib。在

相关问题 更多 >