How to put the legend out of the plot

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

    Short answer: you can use bbox_to_anchor + bbox_extra_artists + bbox_inches='tight'.


    Longer answer: You can use bbox_to_anchor to manually specify the location of the legend box, as some other people have pointed out in the answers.

    However, the usual issue is that the legend box is cropped, e.g.:

    import matplotlib.pyplot as plt
    
    # data 
    all_x = [10,20,30]
    all_y = [[1,3], [1.5,2.9],[3,2]]
    
    # Plot
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    
    # Add legend, title and axis labels
    lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
    ax.set_title('Title')
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')
    
    fig.savefig('image_output.png', dpi=300, format='png')
    

    enter image description here

    In order to prevent the legend box from getting cropped, when you save the figure you can use the parameters bbox_extra_artists and bbox_inches to ask savefig to include cropped elements in the saved image:

    fig.savefig('image_output.png', bbox_extra_artists=(lgd,), bbox_inches='tight')

    Example (I only changed the last line to add 2 parameters to fig.savefig()):

    import matplotlib.pyplot as plt
    
    # data 
    all_x = [10,20,30]
    all_y = [[1,3], [1.5,2.9],[3,2]]
    
    # Plot
    fig = plt.figure(1)
    ax = fig.add_subplot(111)
    ax.plot(all_x, all_y)
    
    # Add legend, title and axis labels
    lgd = ax.legend( [ 'Lag ' + str(lag) for lag in all_x], loc='center right', bbox_to_anchor=(1.3, 0.5))
    ax.set_title('Title')
    ax.set_xlabel('x label')
    ax.set_ylabel('y label')    
    
    fig.savefig('image_output.png', dpi=300, format='png', bbox_extra_artists=(lgd,), bbox_inches='tight')
    

    enter image description here

    I wish that matplotlib would natively allow outside location for the legend box as Matlab does:

    figure
    x = 0:.2:12;
    plot(x,besselj(1,x),x,besselj(2,x),x,besselj(3,x));
    hleg = legend('First','Second','Third',...
                  'Location','NorthEastOutside')
    % Make the text of the legend italic and color it brown
    set(hleg,'FontAngle','italic','TextColor',[.3,.2,.1])
    

    enter image description here

提交回复
热议问题