2017-08-24 85 views
0

下面是一段代碼,僅用於說明line1和line2的尺寸與line3的尺寸不同。你將如何在同一個圖上繪製這幾行。就目前而言,matplotlib會拋出一個異常。python matplotlib對於同一圖上的多個圖的不等尺寸

def demo(): 
    x_line1, y_line1 = np.array([1,2,3,4,5]), np.array([1,2,3,4,5]) 
    x_line2, y_line2 = np.array([1,2,3,4,5]), 2*y_line1 
    x_line3, y_line3 = np.array([1,2,3]), np.array([3,5,7]) 
    plot_list = [] 
    plot_list.append((x_line1, y_line1, "attr1")) 
    plot_list.append((x_line2, y_line2, "attr2")) 
    plot_list.append((x_line3, y_line3, "attr3")) 

    #Make Plots 
    title, x_label, y_label, legend_title = "Demo", "X-axis", "Y-axis", "Legend" 
    plt.figure() 
    for line_plt in plot_list: 
     plt.plot(line_plt[0], line_plt[1], label=line_plt[2]) 
    plt.title(title) 
    plt.xlabel(x_label) 
    plt.ylabel(y_label) 
    plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left", borderaxespad=0, title=legend_title) 
    plt.show() 
+0

鱈魚e如問題所示是正確的。如果你得到一個異常(錯誤),你需要包括完整的錯誤追溯以及你的庫的版本,並使代碼成爲[mcve](即添加導入並清楚說明你如何運行它)。使用'hold = True'已被棄用,不太可能成爲任何問題的嚴肅解決方案。 – ImportanceOfBeingErnest

回答

0

原來所需要的是增加「3.0 axes.hold已過時,將被刪除」的「持有」作爲this answer詳細說明,即使它給

warnings.warn( )

所以,完整的解決方案,以我的未來自己和他人是

def demo(): 
    x_line1, y_line1 = np.array([1,2,3,4,5]), np.array([1,2,3,4,5]) 
    x_line2, y_line2 = np.array([1,2,3,4,5]), 2*y_line1 
    x_line3, y_line3 = np.array([1,2,3]), np.array([3,5,7]) 
    plot_list = [] 
    plot_list.append((x_line1, y_line1, "attr1")) 
    plot_list.append((x_line2, y_line2, "attr2")) 
    plot_list.append((x_line3, y_line3, "attr3")) 

    title, x_label, y_label, legend_title = "Demo", "X", "Y", "Legend" 
    plt.figure() # add this to allow for different lengths 
    plt.hold(True) 
    for line_plt in plot_list: 
     plt.plot(line_plt[0], line_plt[1], label=line_plt[2]) 
    plt.title(title) 
    plt.xlabel(x_label) 
    plt.ylabel(y_label) 
    plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left", borderaxespad=0, title=legend_title) 
    plt.show()