How to put the legend out of the plot

后端 未结 17 3146
时光说笑
时光说笑 2020-11-21 04:42

I have a series of 20 plots (not subplots) to be made in a single figure. I want the legend to be outside of the box. At the same time, I do not want to change the axes, a

17条回答
  •  伪装坚强ぢ
    2020-11-21 05:35

    It's worth refreshing this question, as newer versions of Matplotlib have made it much easier to position the legend outside the plot. I produced this example with Matplotlib version 3.1.1.

    Users can pass a 2-tuple of coordinates to the loc parameter to position the legend anywhere in the bounding box. The only gotcha is you need to run plt.tight_layout() to get matplotlib to recompute the plot dimensions so the legend is visible:

    import matplotlib.pyplot as plt
    
    plt.plot([0, 1], [0, 1], label="Label 1")
    plt.plot([0, 1], [0, 2], label='Label 2')
    
    plt.legend(loc=(1.05, 0.5))
    plt.tight_layout()
    

    This leads to the following plot:

    References:

    • https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html
    • https://showmecode.info/matplotlib/legend/reposition-legend/ (personal site)

提交回复
热议问题