如何基于第三维为时间步的3D数组为Python pcolormesh制作动画
问题原因
你的代码没有实现预期动画效果,主要有3个核心问题:
- 扩散迭代的核心公式写错,没有叠加当前时刻的浓度值,导致除初始帧外所有时间步的浓度都远低于初始值,肉眼几乎看不到变化
- 边界循环没有做越界处理,i=0、j=0时会取到数组末尾的错误值,迭代结果不符合真实扩散规律
- 动画函数每次都新建
pcolormesh绘图对象叠加在画布上,没有更新初始绘图对象的数据,也没有固定色阶范围,动态适配的色阶会进一步掩盖数值变化
修复后可运行代码
from matplotlib.animation import FuncAnimation import numpy as np import matplotlib.pyplot as plt # 扩散过程计算代码(已修复迭代逻辑) grid_size = 100 t_iter = 1000 D = .01 length = 1.0 tmax = 1.0 dx = dy = length/grid_size dt = tmax/t_iter rho = np.zeros((grid_size, grid_size, t_iter)) rho[grid_size//2, grid_size//2, 0] = 1.2 # 初始配置 for n in range(t_iter-1): # 跳过边界网格,避免索引越界 for j in range(1, grid_size-1): for i in range(1, grid_size-1): pxx = rho[i+1,j,n] + rho[i-1,j,n] - 2*rho[i,j,n] pyy = rho[i,j+1,n] + rho[i,j-1,n] - 2*rho[i,j,n] # 补充当前时刻浓度,修正迭代公式 rho[i,j,n+1] = rho[i,j,n] + D*dt*(pxx/dx**2+pyy/dy**2) # 动画部分代码(已修复刷新逻辑) fig, ax = plt.subplots() # 固定色阶范围,保证数值变化可见 vmin = rho.min() vmax = rho.max() mesh = ax.pcolormesh(rho[:,:,0], vmin=vmin, vmax=vmax) plt.colorbar(mesh, ax=ax) def animate(i): # 仅更新已有绘图对象的数据,不新建图层 mesh.set_array(rho[:,:,i].ravel()) return mesh, anim = FuncAnimation(fig, animate, interval=10, frames=t_iter-1, repeat=False, blit=True) plt.show()
可选优化说明
- 开启
blit=True参数可以只刷新画布上变化的区域,大幅提升动画流畅度 - 如果需要保存动画,可以在
plt.show()前调用anim.save('diffusion.gif', writer='pillow')保存为gif格式,保存为mp4需要提前安装ffmpeg
内容的提问来源于stack exchange,提问作者Earthling75
相关产品推荐
相关产品推荐

