2017-08-24 82 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()