python - Matplotlib animation with time-dependent parameter
问题描述
I am new using python and I would like to ask you a problem that I have with my current code. I am solving a partial differential equation (1D in space) and I want to make an animation at each time for the given numerical solution, but I don't want to save all the arrays of the solution at each time (because this is not efficient)
For simplicity I just show you the analytical solution of the differential equation.
I have tried to make a plot for each time steep trying to make an animation, but as I have read in other places it's not too much efficient due to the 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()
Do you know how can be re-implemented my code to make an animation (and save it) without save the data ?
解决方案
Here is how to use FuncAnimation
to generate the desired animation
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()
推荐阅读
- javascript - 即使使用 g 标志,String.match 也只返回第一个匹配项
- r - 使用 R 未来包的最大并行进程数
- caching - 单次调用从 Redis 缓存中查询百万键
- node.js - Big Bule Button的集成
- amazon-web-services - AWS Elastic Beanstalk 上的 Axios CORS 问题
- mongodb - 需要将用户 ID 数组转换为 ObjectId 以在聚合函数中使用
- java - Windows CMD 无法调用另一个类
- html - 为什么我不能在 H1 标签中使用 padding-left
- javascript - 尝试将记录发送到数据库时出现 404 错误
- c# - 如何在插入 MYSQL 之前获取下一个自动增量 ID