Python matplotlib在同一图上的多个图的不等尺寸

时间:2017-08-24 18:50:17

标签: python matplotlib plot

以下是一段代码,仅用于说明第1行和第2行的维度与第3行的维度不同。你会如何在同一个地块上绘制这几行?就目前而言,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()

1 个答案:

答案 0 :(得分:0)

原来所需要的是添加" hold"详见this answer,尽管它给出了

  

warnings.warn("不推荐使用axes.hold,将在3.0和#34中删除;)

所以,对我未来的自我和他人的完整解决方案是

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()