【问题标题】:how do i overwrite plot for iterative in python我如何在python中覆盖迭代的情节
【发布时间】:2020-12-02 12:14:39
【问题描述】:

我想用隐式 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。但也没有为我工作。是否可以在图中为每个图赋予不同的颜色和标签? 任何建议都会有所帮助!

【问题讨论】:

    标签: python numpy matplotlib iteration pde


    【解决方案1】:

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

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

    【讨论】:

    • 啊,我明白了。工作完美!但是你知道为什么 plt.ion() 和 plt.pause() 我看到很多人建议对我不起作用吗?我将如何实现它?
    • 遗憾的是,我没有使用 plt.pause 或 plit.ion 的经验,但它似乎对不同的应用程序有帮助,而不是你对这个脚本的需要。如果我的答案是您正在寻找的答案,请用勾号将其标记为已接受:)。
    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2014-06-08
    • 2020-03-07
    • 2016-10-10
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多