1

I am trying to produce a giF to represent the change of a plot over time in python. However, I am getting separate plots for each graph (they are not stacking on the same plot). I am fresh at coding and would appreciate any insight. The part of the code:

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)
  • Does this answer your question? [How to update a plot in matplotlib](https://stackoverflow.com/questions/4098131/how-to-update-a-plot-in-matplotlib) – FlyingTeller Jul 24 '23 at 07:02
  • Please provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). You have omitted some important information, such as how `x`, `T1`, `T2`, `dT1dt`, `dT2dt`, `dt`, and `L` are defined. – jared Jul 24 '23 at 07:03

1 Answers1

0

You can use the imageio library

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()

then

for t in your_t_variable:
    make_frame(t)

after that, in a different script, or in the same if you prefer

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

and then, atlast

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