为了账号安全,请及时绑定邮箱和手机立即绑定

具有时间相关参数的 Matplotlib 动画

具有时间相关参数的 Matplotlib 动画

饮歌长啸 2021-10-26 10:51:51
我是使用 python 的新手,我想问你一个我当前代码的问题。我正在求解一个偏微分方程(空间中的一维),我想每次都为给定的数值解制作动画,但我不想每次都保存解的所有数组(因为这不是高效的)为简单起见,我只向您展示微分方程的解析解。我试图为每次尝试制作动画都制作一个陡峭的情节,但正如我在其他地方读到的那样,由于 plt.pause()import numpy as npimport mathfrom matplotlib import pyplot as pltpi = math.pixmin = 0.0xmax = 10.0N = 100 #number of pointsx = 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 pt_final = 10.0t_initial = 0.0t = t_initialdt = 0.1k = 1.0while 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()您知道如何在不保存数据的情况下重新实现我的代码以制作动画(并保存)吗?
查看完整描述

2 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

这种方式使用了我写的一个库,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')


查看完整回答
反对 回复 2021-10-26
  • 2 回答
  • 0 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号