循环遍历在Python中返回函数图的子图

时间:2017-07-25 03:18:35

标签: python matplotlib

我正在尝试为高斯函数循环n行2列的子图,如下面的示例代码所示。这会返回直方图和正态分布,我尝试了几种方法失败,任何帮助都是最受欢迎的。

Speed = [0,10,20,30,40]
Torque1 = []
Torque2 = []
for i in range(5):
    Trq = np.random.normal(0, 10, 5)
    Torque1.append(Trq)
for i in range(5):
    Trq = np.random.normal(0, 10, 5)
    Torque2.append(Trq)    

def gaussian_Histo(s, Title):
    mu, sigma = np.mean(s), np.std(s, ddof=1) # mean and standard deviation
    fig = plt.figure(Title, figsize=(10, 6), dpi=80)
    count, bins, ignored = plt.hist(s, 80, normed=True)
    plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r')
    plt.grid(True)
    plt.title(Title)
    plt.show()

def main():
    nrows = 3
    fig, axes = plt.subplots(nrows, 2)

    for row in axes:
#     for i in range(3):
        x = gaussian_Histo(Torque1[i], 'Torque at'+str(Speed[i])+'RPM')
        y = gaussian_Histo(Torque2[i], 'Torque at'+str(Speed[i])+'RPM')
        plot(row, x, y)

    plt.show()

def plot(axrow, x, y):
    axrow[0].plot(x, color='red')
    axrow[1].plot(y, color='green')

main()

2 个答案:

答案 0 :(得分:0)

您看到该错误的原因是您没有从SaveChanges()返回任何值,因此正在尝试绘制DBContext

我已经删除了单独绘制每个直方图的代码部分,因为这将中断您的网格绘图,除非您更改创建该数字的方式。因此,我使用了gaussian_Histo而不是x = Nonenp.histogram实际上在幕后使用plt.hist

示例:

plt.hist

这产生了数字:

enter image description here

答案 1 :(得分:0)

我想出了单独绘制直方图的代码。我修改了我的绘图功能(gaussian_Histo),返回单个绘图。

Speed = [0,10,20,30,40]
Torque1 = []
Torque2 = []
for i in range(5):
    Trq = np.random.normal(0, 10, 5)
    Torque1.append(Trq)
for i in range(5):
    Trq = np.random.normal(0, 10, 5)
    Torque2.append(Trq)    
# print(Torque1)
def gaussian_Histo(s, Title, ax = None):
    mu, sigma = np.mean(s), np.std(s, ddof=1) # mean and standard deviation
    if ax is None:
        ax = plt.gca()
    count, bins, ignored = ax.hist(s, 80, normed=True)
    ax.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (bins - mu)**2 / (2 * sigma**2) ), linewidth=2, color='r')
    ax.grid(True)
    ax.set_title(Title)
    plt.show()
for i in range(len(Speed)):
    f, (ax1, ax2) = plt.subplots(1, 2, sharey=False, figsize=(8,6), dpi=50) 
    gaussian_Histo(Torque1[i], 'Torque1 at '+str(Speed[i])+'RPM', ax1)
    gaussian_Histo(Torque2[i], 'Torque2 at '+str(Speed[i])+'RPM', ax2)

Individual Plot Results in this link