我正在尝试生成一个 gif 来表示 python 中绘图随时间的变化。但是,我为每个图表获取单独的图(它们没有堆叠在同一个图上)。我对编码很陌生,希望能得到任何见解。部分代码:
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)
您可以使用
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
基于@HarshNJ答案,我在下面提供了一个答案,避免了将图像保存到磁盘然后读取它们的步骤。
import imageio
import numpy as np
frames = []
for t in time_array:
fig = plot_gif_frame(t)
fig.canvas.draw()
frames.append(np.array(fig.canvas.renderer._renderer))
# Save GIF
imageio.mimsave('my_animation.gif', # output gif
frames, # array of input frames
loop = 4, # optional: loops on the final gif
fps=5) # optional: frames per second
其中
plot_gif_frame(t)
将是在时间 t
绘制给定帧的函数,并从 matplotlib.pyplot 返回一个 figure 对象。