我是新使用python,我想问你,我有我当前的代码有问题。我解决偏微分方程(1D空间),我想使每次给定的数值解的动画,但我不想解决方案的所有的数组保存每个时间(因为这是不高效)
为简单起见我只是告诉你微分方程的解析解。
我试图让每次陡峭试图使动画情节,但正如我在其他地方已经阅读它没有太多eficient由于plt.pause()
import numpy as np
import math
from matplotlib import pyplot as plt
pi = math.pi
xmin = 0.0
xmax = 10.0
N = 100 #number of points
x = np.arange(xmin, xmax , (xmax-xmin)/N)
def solution(t):
p = np.exp(-x**2/(4*k*t))/(np.sqrt(4.*pi*k*t))
return p
t_final = 10.0
t_initial = 0.0
t = t_initial
dt = 0.1
k = 1.0
while t<t_final:
t +=dt
pp = solution(t)
plt.ion()
plt.xlabel('x')
plt.ylabel('P')
plt.plot(x, pp, 'r-',label = "t=%s" % t)
plt.legend(loc='upper right')
plt.draw()
plt.pause(10**(-20))
plt.show()
plt.clf()
你知道如何重新实现我的代码来制作动画(并保存),而不保存数据?非常感谢你!!
下面是如何使用FuncAnimation
来生成所需的动画
import numpy as np
import math
from matplotlib import pyplot as plt
pi = math.pi
xmin = 0.0
xmax = 10.0
N = 100 #number of points
x = np.arange(xmin, xmax , (xmax-xmin)/N)
t_initial = 0.0
t_final = 10.0
dt = 0.1
k = 1.0
fig, ax = plt.subplots()
ax.set_xlabel('x')
ax.set_ylabel('P')
plotLine, = ax.plot(x, np.zeros(len(x))*np.NaN, 'r-')
plotTitle = ax.set_title("t=0")
ax.set_ylim(0,1.)
ax.set_xlim(xmin,xmax)
def solution(t):
p = np.exp(-x**2/(4*k*t))/(np.sqrt(4.*pi*k*t))
return p
def animate(t):
pp = solution(t)
plotLine.set_ydata(pp)
plotTitle.set_text(f"t = {t:.1f}")
#ax.relim() # use if autoscale desired
#ax.autoscale()
return [plotLine,plotTitle]
ani = animation.FuncAnimation(fig, func=animate, frames=np.arange(t_initial, t_final+dt, dt), blit=True)
plt.show()
这样使用我写了一个库,celluloid。有了它,我只有在自己的代码改动线路了一把:主要与赛璐珞稍微改变了传说创作了几个电话。
import numpy as np
import math
from matplotlib import pyplot as plt
from celluloid import Camera
pi = math.pi
xmin = 0.0
xmax = 10.0
N = 100 #number of points
x = np.arange(xmin, xmax , (xmax-xmin)/N)
def solution(t):
p = np.exp(-x**2/(4*k*t))/(np.sqrt(4.*pi*k*t))
return p
t_final = 10.0
t_initial = 0.0
t = t_initial
dt = 0.1
k = 1.0
fig = plt.figure()
camera = Camera(fig)
plt.xlabel('x')
plt.ylabel('P')
while t<t_final:
t +=dt
pp = solution(t)
line = plt.plot(x, pp, 'r-')
plt.legend(line, ['t={:.1f}'.format(t)], loc='upper right')
camera.snap()
animation = camera.animate()
animation.save('animation.mp4')