Search code examples
pythonanimationplot

Is there a way to animate a line plot based on rows in a numpy array?


I have a 2d array (39, 57601) where the columns represent time (57601 time points in total) and rows represent temperature at specific nodal positions (39 nodes in total). In other words, each column in the array describes the temperature profile at the corresponding timepoint. I can create static plots of the temperature profile, but I want to visualise how the temperature profile evolves with time. I want each line to be shown individually on a plot, then move onto the next line after 0.1(?) seconds, and so on.

I've provided some basic code below to represent the data.

import numpy as np
import matplotlib.pylab as plt

#creating some dummy data (4 nodes, 5 timepoints) - values not important

T1 = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
T2 = T1**2
T3 = T1**3
T4 = T1**4
T=np.stack((T1, T2, T3, T4))

position = np.array([0, 2, 4, 6])

#visualising all lines at once

plt.plot(position,T[:,0], label='0s', marker='o')
plt.plot(position,T[:,1], label='10s', marker='o')
plt.plot(position,T[:,2], label='20s', marker='o')
plt.plot(position,T[:,3], label='30s', marker='o')
plt.plot(position,T[:,4], label='40s', marker='o')
plt.legend()
plt.xlabel('Position (mm)')
plt.ylabel('Temperature (C)')
plt.show()


Solution

  • You could use matplotlib.animation.FuncAnimation - see https://matplotlib.org/stable/api/_as_gen/matplotlib.animation.FuncAnimation.html

    import numpy as np
    import matplotlib.pylab as plt
    import matplotlib.animation as animation
    
    #creating some dummy data (4 nodes, 5 timepoints) - values not important
    
    T1 = np.array([1.1, 1.2, 1.3, 1.4, 1.5])
    T2 = T1**2
    T3 = T1**3
    T4 = T1**4
    T=np.stack((T1, T2, T3, T4))
    
    position = np.array([0, 2, 4, 6])
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    a = ax.plot( position,T[:,0], label='0 s', marker='o' )
    ax.set_xlabel('Position (mm)')
    ax.set_ylabel('Temperature (C)')
    ax.set_ylim( top=6 )
    ax.legend( loc='upper left' )
    
    def animate( i ):                           # update anything that has changed
        a[0].set_label( f'{(i+1)*10} s' )
        ax.legend( loc='upper left' )
        a[0].set_data( position, T[:,i+1] )
    ani = animation.FuncAnimation( fig, animate, interval=1000, frames=len(T), repeat=False )
    
    plt.show()
    #ani.save( "demo.gif", fps=1 )