Search code examples
pythonmatplotliblegend

Do gca().lines and legend.get_lines() return the lines in the same order?


Do gca().lines and legend.get_lines() return the lines in the same corresponding order?

If not, is there a way to get corresponding legend lines from gca().lines?


Solution

  • Let's check.

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.plot([0, 1], [0, 1], label="test1")
    ax.plot([1, 2], [3, 5], label="test2")
    ax.plot([6, 7], [8, 9], label="test3")
    legend = ax.legend()
    
    for ax_line, legend_line in zip(ax.lines, legend.get_lines()):
        print(ax_line.get_label(), legend_line.get_label())
    

    Output:

    test1 test1
    test2 test2
    test3 test3
    

    Looks like they do. In other words, ax.lines and legend.get_line() both store the lines in the order they were created.

    Edit: See JohanC's disclaimer below my answer. My answer assumes the plots are simple line or scatter plots and the legend is automatically created. And if only some lines have labels, then the line orders will still be the same but ax.lines will have more lines than legend.get_lines().