我是使用python的新手,我想问一个问题,我的当前代码有问题。我正在求解一个偏微分方程(空间中为1D),我想每次为给定的数值解制作一个动画,但是我不想每次都保存解的所有数组(因为这不是高效)
为简单起见,我仅向您展示微分方程的解析解。
每次尝试制作动画时,我都试图绘制一个陡峭的图,但是正如我在其他地方所读到的那样,由于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()
您知道如何在不保存数据的情况下重新实现我的代码以制作动画(并保存动画)吗?非常感谢你!
答案 0 :(得分:3)
以下是使用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()
答案 1 :(得分:0)
此方式使用库我写,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')