Search code examples
pythonmatplotliblegendaxes

Matlplotlib plot with inset: make legend in original axis


I have a very simple question that I can't find the answer to:

Using matplotlib I plot something in a main plot and then something else in an inset using e.g.

a = plt.axes([.2, .64, .28, .24])

But after that I want to plot a legend in the main plot again (because the legend contains something found in the meantime).

How do I do this? As in how do I go back to the original plot and make the legend?

I tried different things including sca, but nothing has worked.


Solution

  • plt.sca(main_ax) should have worked. Note that if you didn't specify a label for the curve/plot/etc, it won't be shown if you only call plt.legend(). (Instead, you'd need to do plt.legend([line], [label]), or better yet, call plot(x, y, label='some label').)

    However, it's better to approach the problem a different way.

    This is one of the many reasons why you'll often see people recommend avoiding the pyplot interface and using Axes/Figure methods instead. It makes it very clear which axes you're operating on.

    For example:

    import matplotlib.pyplot as plt
    
    fig, ax = plt.subplots()
    ax.plot(range(10), label='Curve 1')
    
    inset = fig.add_axes([.2, .64, .28, .24])
    inset.scatter(range(3), range(3))
    
    ax.legend()
    
    plt.show()
    

    enter image description here