【问题标题】:My animation is not graphing properly我的动画无法正确绘制
【发布时间】:2026-01-15 23:20:10
【问题描述】:

问题

我需要动画流畅,但它是逐帧绘制的。代码在 Jupyter Notebook 中运行。

这里是库

import numpy as np
from matplotlib import pyplot as plt
from scipy import signal as sp

创建要卷积的函数

t_ini=0
t_final = 11
dt=0.1
t = np.arange(t_ini,t_final,dt)
expo = np.exp(-t)*np.piecewise(t,t>=0,[1,0])
t1 = np.arange(0,10,0.1)
s = np.sin(t1)
conv_=sp.convolve(s,expo,'full')
n_conv=np.arange(min(t1)+min(t),max(t1)+max(t)+0.1,0.1)
y = [0] * len(conv_)
t2 = [0] * len(n_conv)

这是绘图

i = 0
for x in n_conv:

    y[i] = conv_[i]
    plt.cla()
    t2[i] = n_conv[i]
    plt.plot(t2,y)
    plt.show()
    plt.pause(0.5)

    i = i+1

【问题讨论】:

    标签: python python-3.x matplotlib scipy jupyter-notebook


    【解决方案1】:

    matplotlib 提供例如ArtistAnimation,它允许预先计算的图形的无缝动画。我刚刚在您的代码中添加了几行。我唯一改变的是使用enumerate 来改进你的代码

    import numpy as np
    from matplotlib import pyplot as plt
    from scipy import signal as sp
    import matplotlib.animation as anim
    
    t_ini=0
    t_final = 11
    dt=0.1
    t = np.arange(t_ini,t_final,dt)
    expo = np.exp(-t)*np.piecewise(t,t>=0,[1,0])
    t1 = np.arange(0,10,0.1)
    s = np.sin(t1)
    conv_=sp.convolve(s,expo,'full')
    n_conv=np.arange(min(t1)+min(t),max(t1)+max(t)+0.1,0.1)
    y = [0] * len(conv_)
    t2 = [0] * len(n_conv)
    
    #prepare figure for display
    fig = plt.figure()
    ax = plt.axes()
    
    #create list to collect graphs for animation
    img = []
    for i, x in enumerate(n_conv):
    
        y[i] = conv_[i]
        t2[i] = n_conv[i]
        #append new graphs to  list
        newpic, = ax.plot(t2, y, c= "blue")
        img.append([newpic])
    
    #animate the list of precalculated graphs
    ani = anim.ArtistAnimation(fig, img, interval = 50)
    plt.show()
    

    输出:

    【讨论】:

    • 那里出了点问题,只是给了我一个空白图表
    • 嗯。我刚刚将此代码粘贴到我的 IDE 中,它会为曲线设置动画。你的 matplotlib 版本和你的后端是什么?
    • 我的 matplotlib 版本是 2.0.0 你说我的后端是什么意思?
    • 好的,当我从 .py 文件中的 cli 运行它时,它可以很好地为曲线设置动画,但在 jupyter notebook 中它不起作用。为什么会发生这种情况?
    • 我不使用jupyter notebook,但是貌似有些后端不支持动画,看这里:*.com/a/46878531/8881141或者这里:*.com/a/43447370/8881141
    最近更新 更多