Search code examples
pythonnumpymatplotlibiterationpde

how do i overwrite plot for iterative in python


i want to plot a 1D Heat Diffusion with implicit PDE. here is the problem Heat Diffusion. here's the PDE equation. my code is fine but it creates a new figure for each iteration.

import numpy as np
import matplotlib.pyplot as plt

L = 0.05  #length
n = 5 #number of segment
T0 = 20  #initial temperature
T1s = 100 #boundary condition in segment 0
T2s = 25 #boundary condition in segment 5
dx = L/n #delta x
alpha = 0.000014129 #heat coeff
t_final = 9  
dt = 3

x = np.linspace(0, L, n+1)

T = np.ones(n+1)*T0 #array of Temperature initial condition
dTdt = np.empty(n+1) #dTdt delta T /delta t

t = np.arange(0, t_final, dt)

for j in range(1,len(t)+1):
    for i in range(1, n):
        dTdt[i] = alpha*(T[i+1]-2*T[i]+T[i-1])/dx**2   #PDE iterative function for segment i
    dTdt[0] = alpha*(T[1]-2*T[0]+T1s)/dx**2       
    dTdt[n-1] = alpha*(T[n-2]-2*T[n-1]+T2s)/dx**2    
    T = T + dTdt*dt
    T[0]=T1s
    T[5]=T2s
    plt.figure(1)
    plt.plot(x,T)
    plt.axis([-0.01, L+0.01, 0, 120])
    plt.xlabel('Distance (m)')
    plt.ylabel('Temperature (C)')
    plt.show()

i've added plt.ion() and plt.pause() but it didnt work. i also tried similar PDE plotting. but didnt work for me either. also is it possible to give each plot a different color and label in the figure? any suggestion would help !


Solution

  • You can create the figure instance before the loop and add the figures + labels in the loop as follows:

    import numpy as np
    import matplotlib.pyplot as plt
    
    L = 0.05  #length
    n = 5 #number of segment
    T0 = 20  #initial temperature
    T1s = 100 #boundary condition in segment 0
    T2s = 25 #boundary condition in segment 5
    dx = L/n #delta x
    alpha = 0.000014129 #heat coeff
    t_final = 9  
    dt = 3
    
    x = np.linspace(0, L, n+1)
    
    T = np.ones(n+1)*T0 #array of Temperature initial condition
    dTdt = np.empty(n+1) #dTdt delta T /delta t
    
    t = np.arange(0, t_final, dt)
    fig, ax = plt.subplots(figsize = (8,6))
    for j in range(1,len(t)+1):
        for i in range(1, n):
            dTdt[i] = alpha*(T[i+1]-2*T[i]+T[i-1])/dx**2   #PDE iterative function for segment i
        dTdt[0] = alpha*(T[1]-2*T[0]+T1s)/dx**2       
        dTdt[n-1] = alpha*(T[n-2]-2*T[n-1]+T2s)/dx**2    
        T = T + dTdt*dt
        T[0]=T1s
        T[5]=T2s
        ax.plot(x,T,label = 'Iteration' + ' ' + str(j))
        
    ax.legend()
    ax.axis([-0.01, L+0.01, 0, 120])
    ax.set_xlabel('Distance (m)')
    ax.set_ylabel('Temperature (C)');