How to put the legend out of the plot

后端 未结 17 3233
时光说笑
时光说笑 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:21

    • You can make the legend text smaller by specifying set_size of FontProperties.
    • Resources:
      • Legend guide
      • matplotlib.legend
      • matplotlib.pyplot.legend
      • matplotlib.font_manager
        • set_size(self, size)
        • Valid font size are xx-small, x-small, small, medium, large, x-large, xx-large, larger, smaller, None
      • Real Python: Python Plotting With Matplotlib (Guide)
    import matplotlib.pyplot as plt
    from matplotlib.font_manager import FontProperties
    
    fontP = FontProperties()
    fontP.set_size('xx-small')
    
    p1, = plt.plot([1, 2, 3], label='Line 1')
    p2, = plt.plot([3, 2, 1], label='Line 2')
    plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', prop=fontP)
    

    • As noted by Mateen Ulhaq, fontsize='xx-small' also works, without importing FontProperties.
    plt.legend(handles=[p1, p2], title='title', bbox_to_anchor=(1.05, 1), loc='upper left', fontsize='xx-small')
    

提交回复
热议问题