我如何在 python 中覆盖迭代图

how do i overwrite plot for iterative in python

我想用隐式 PDE 绘制一维热扩散。这是问题Heat Diffusion. here's the PDE equation。 我的代码很好,但它会为每次迭代创建一个新图形。

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

我已经添加了 plt.ion() 和 plt.pause() 但它没有用。我也试过similar PDE plotting。但也没有为我工作。也可以在图中为每个图赋予不同的颜色和标签吗? 任何建议都会有所帮助!

您可以在循环之前创建图形实例,并在循环中添加图形+标签,如下所示:

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)');