matplotlib 制作一个随时间变化的python图形的GIF?

4urapxun  于 2023-08-06  发布在  Python
关注(0)|答案(1)|浏览(110)

我试图在python中生成一个giF来表示一个图随时间的变化。然而,我正在为每个图获得单独的图(它们不是堆叠在同一个图上)。我是新的编码,并会欣赏任何见解。代码部分:

import numpy as np
import matplotlib.pyplot as plt

t = np.arange(0,t_final, dt)
x = np.linspace(dx/2, L-dx/2, n)

T1 = np.ones(n)*T0
dT1dt = np.zeros(n)

T2 = np.ones(n)*T0
dT2dt = np.zeros(n)

for j in range(1,len(t)):
  
    plt.clf()

    T1 = T1 + dT1dt*dt #T1 is an array
    T2 = T2 + dT2dt*dt #T2 is an array

    plt.figure(1)
    plt.plot(x,T1,color='blue', label='Inside')
    plt.plot(x,T2,color='red', label='Outside')
    plt.axis([0, L, 298, 920])
    plt.xlabel('Distance (m)')
    plt.ylabel('Temperature (K)')
    plt.show()
    plt.pause(0.005)

字符串

nnt7mjpx

nnt7mjpx1#

您可以使用imageio

import imageio

def make_frame(t):
    fig = plt.figure(figsize=(6, 6))
    # do your stuff
    plt.savefig(f'./img/img_{t}.png', transparent=False, facecolor='white')
    plt.close()

字符串
然后,

for t in your_t_variable:
    make_frame(t)


在那之后,在不同的脚本中,或者在相同的脚本中,如果你喜欢

frames = []
for t in time:
    image = imageio.v2.imread(f'./img/img_{t}.png')
    frames.append(image)


然后,最后

imageio.mimsave('./example.gif', # output gif
                frames,          # array of input frames
                fps=5)         # optional: frames per second

相关问题