由于x和y数组的大小,无法绘制

时间:2022-02-06 23:07:28

I am trying to produce a number of plots of temperature (te) versus time (t), where for each plot, a different timestep (dt) is used to calculate the temperature. 由于x和y数组的大小,无法绘制. Initially my code ran fine and I produced the plot shown (the plot is made up of a number of plots, more visible when zoomed in). However after making an adjustment to my values for dt_values I have not been able to run the code, and am getting the 'x and y must have same first dimension' error message but I cannot see why.

我试图产生许多温度(te)对时间(t)的曲线图,其中对于每个曲线,使用不同的时间步长(dt)来计算温度。 。最初我的代码运行正常并且我生成了所显示的绘图(绘图由多个绘图组成,放大时更加明显)。但是在对dt_values的值进行调整后,我无法运行代码,并且得到'x和y必须具有相同的第一维'错误消息,但我不明白为什么。

import numpy as np 
import matplotlib.pyplot as plt


r = 0.024 #cooling rate per minute
te_init = 90.0

te_surr = 17

dt_values = [0.05, 0.025, 0.01, 0.005, 0.001]

for j in dt_values:
    t = np.arange(0,100,j)
    te = np.zeros(len(t))
    te[0] = te_init 

    def f(te):
        y = -r*(te - te_surr) # y is the derivative
        return y
    for i in range(1,len(t)):
        te[i] = te[i-1] + f(te[i-1])*j
        plt.plot(t, te[i], label = j)
        plt.xlabel('Time, [min]')
        plt.ylabel('Temperature, [C]')
        plt.title('Adaptive Time Steps')
        plt.legend(loc=4)

1 个解决方案

#1


1  

You need to plot outside the loop, which populates the temperature array. Then plt.plot(t, te) is working as expected.

您需要在循环外部绘制,填充温度数组。然后plt.plot(t,te)按预期工作。

import numpy as np 
import matplotlib.pyplot as plt


r = 0.024 #cooling rate per minute
te_init = 90.0
te_surr = 17

def f(te):
    return -r*(te - te_surr) # the derivative

dt_values = [20, 5, 1, 0.1, 0.05]

for dt in dt_values:
    t = np.arange(0,100,dt)
    te = np.zeros(len(t))
    te[0] = te_init 

    for i in range(1,len(t)):
        te[i] = te[i-1] + f(te[i-1])*dt

    plt.plot(t, te, label = dt)

plt.xlabel('Time, [min]')
plt.ylabel('Temperature, [C]')
plt.title('Adaptive Time Steps')
plt.legend(loc=4, title="Timestep [min]")

plt.show()

由于x和y数组的大小,无法绘制

#1


1  

You need to plot outside the loop, which populates the temperature array. Then plt.plot(t, te) is working as expected.

您需要在循环外部绘制,填充温度数组。然后plt.plot(t,te)按预期工作。

import numpy as np 
import matplotlib.pyplot as plt


r = 0.024 #cooling rate per minute
te_init = 90.0
te_surr = 17

def f(te):
    return -r*(te - te_surr) # the derivative

dt_values = [20, 5, 1, 0.1, 0.05]

for dt in dt_values:
    t = np.arange(0,100,dt)
    te = np.zeros(len(t))
    te[0] = te_init 

    for i in range(1,len(t)):
        te[i] = te[i-1] + f(te[i-1])*dt

    plt.plot(t, te, label = dt)

plt.xlabel('Time, [min]')
plt.ylabel('Temperature, [C]')
plt.title('Adaptive Time Steps')
plt.legend(loc=4, title="Timestep [min]")

plt.show()

由于x和y数组的大小,无法绘制