You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Matplotlib动画保存问题:如何导出完整20秒而非仅前5秒动画?

解决Matplotlib动画保存不完整的问题

看起来你遇到的问题是因为FuncAnimation默认只生成100帧动画,而你的interval设为50ms,100*50ms刚好是5秒,所以保存出来的动画只有前5秒。要保存完整的20秒动画,我们需要调整几个关键参数:

问题根源

当你没有给animation.FuncAnimation指定frames参数时,它默认只会生成100帧。你的每帧间隔是50ms,100帧总时长就是5秒,这就是为什么保存的动画只到5秒就结束了。

解决方案

1. 调整逻辑匹配20秒时长(推荐)

首先计算需要的总帧数:20秒动画,每帧间隔50ms,总帧数为 20 * 1000 / 50 = 400 帧。同时调整时间计算逻辑,让t和实际动画时长对应:

import math
import matplotlib.pyplot as plt
from matplotlib import animation

# 假设你已经定义了hbar, p1, p2, E1, E2, x这些变量
n = 400  # 总帧数,对应20秒(400*50ms=20000ms)
def update(curr):
    if curr == n:
        a.event_source.stop()
    # 基于帧序号和间隔计算实际时间
    t = (curr * 50) / 1000  
    plt.cla()
    # 修正笔误:把for x in x改成遍历你的x数组
    rho_ = [2/(math.pi*(hbar**2)) * math.cos((((p1 - p2)*x_val)/(2*hbar)) + (((E1 - E2)*t)/(2*hbar)))**2 for x_val in x]
    plt.plot(x, rho_)
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.gca().set(yticklabels=[])
    plt.gca().tick_params(left=False)
    plt.gca().set_xlabel("X")
    plt.gca().set_title("Time evolution of probability density")
    plt.annotate(s = f"t = {t:.1f}s", xy = (0.9, 0.9), xycoords="figure fraction", fontsize=10)

fig = plt.figure(figsize=(9, 3.5))
# 指定frames参数为总帧数400
a = animation.FuncAnimation(fig, update, frames=n, interval=50)
# 保存时指定writer确保编码器正常工作
a.save("probability_density_animation.avi", writer='ffmpeg')

2. 保留原时间计算逻辑的调整

如果你想维持原来t = curr/100的计算方式,要让t到20秒,curr需要到2000。但你的update里用curr = curr*10(这里的curr是帧序号),所以帧序号需要到200。此时总帧数是201(从0到200),但201*50ms只有10秒,所以需要把interval改成100ms来凑够20秒:

import math
import matplotlib.pyplot as plt
from matplotlib import animation

# 假设你已经定义了hbar, p1, p2, E1, E2, x这些变量
n = 2000
def update(curr):
    curr_frame = curr*10
    if curr_frame == n:
        a.event_source.stop()
    t = curr_frame / 100
    plt.cla()
    # 修正笔误:把for x in x改成遍历你的x数组
    rho_ = [2/(math.pi*(hbar**2)) * math.cos((((p1 - p2)*x_val)/(2*hbar)) + (((E1 - E2)*t)/(2*hbar)))**2 for x_val in x]
    plt.plot(x, rho_)
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.gca().set(yticklabels=[])
    plt.gca().tick_params(left=False)
    plt.gca().set_xlabel("X")
    plt.gca().set_title("Time evolution of probability density")
    plt.annotate(s = f"t = {t}s", xy = (0.9, 0.9), xycoords="figure fraction", fontsize=10)

fig = plt.figure(figsize=(9, 3.5))
# 指定frames为201(0到200),interval改为100ms
a = animation.FuncAnimation(fig, update, frames=201, interval=100)
a.save("probability_density_animation.avi", writer='ffmpeg')

额外注意事项

  • 确保你已经安装了ffmpeg,可以用pip install ffmpeg-python或者系统包管理器安装,否则保存动画可能会报错。
  • 你原代码里的for x in x是明显的笔误,会导致变量引用错误,一定要改成你实际定义的x数组变量(比如示例中的x_val遍历x)。

内容的提问来源于stack exchange,提问作者sbhhdp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:17:41