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

Python 如何在Matplotlib中设置函数动画,python,animation,matplotlib,Python,Animation,Matplotlib,我试图用无穷级数的定义来近似“e^x”,并把它画在一张图上 无论出于何种原因,此代码都会生成一个对话框,其中有一个绘图,显示时间为几分之一秒,然后以退出代码1结束 我不明白为什么这不起作用。当你计算y时,你有一个输入错误。Python中的求幂运算符是**,而不是^。如果使用y=(x-speed*i)+((x-speed*i)**2)/2+((x-speed*i)**3)/6),则原始问题中的代码运行时不会出错 奇怪的是,你没有得到预期的回溯。例如,如果你尝试 import matplotlib

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

无论出于何种原因,此代码都会生成一个对话框,其中有一个绘图,显示时间为几分之一秒,然后以退出代码1结束


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

当你计算
y
时,你有一个输入错误。Python中的求幂运算符是
**
,而不是
^
。如果使用
y=(x-speed*i)+((x-speed*i)**2)/2+((x-speed*i)**3)/6),则原始问题中的代码运行时不会出错


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

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()
您将得到一个
类型错误

x = np.ones(5)
x ^ 1
回溯(最近一次呼叫最后一次):
文件“C:/Users/joshk/GitHubProjects/stackoverflow/b.py”,第5行,在
x^1
TypeError:输入类型不支持ufunc“按位异或”,并且无法根据强制转换规则“安全”将输入安全强制为任何支持的类型
FuncAnimator
中,此回溯似乎被抑制。我浏览了一下地图,但没有任何东西向我扑来,因为这是造成压制的原因


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

在运行原始代码时,我确实得到了输入类型不支持的
TypeError:ufunc“bitwise\u xor”
错误。因此,我认为在matplotlib代码中的任何地方都不会禁止回溯。可能是因为它被用于运行代码的程序抑制了。回答得很好,很有趣!我在从命令行运行时看到了回溯,但不是从PyCharm中看到的,这一定是PyCharm的问题。
Traceback (most recent call last):
  File "C:/Users/joshk/GitHubProjects/stackoverflow/b.py", line 5, in <module>
    x ^ 1
TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''