How to put the legend out of the plot

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

    Something along these lines worked for me. Starting with a bit of code taken from Joe, this method modifies the window width to automatically fit a legend to the right of the figure.

    import matplotlib.pyplot as plt
    import numpy as np
    
    plt.ion()
    
    x = np.arange(10)
    
    fig = plt.figure()
    ax = plt.subplot(111)
    
    for i in xrange(5):
        ax.plot(x, i * x, label='$y = %ix$'%i)
    
    # Put a legend to the right of the current axis
    leg = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    
    plt.draw()
    
    # Get the ax dimensions.
    box = ax.get_position()
    xlocs = (box.x0,box.x1)
    ylocs = (box.y0,box.y1)
    
    # Get the figure size in inches and the dpi.
    w, h = fig.get_size_inches()
    dpi = fig.get_dpi()
    
    # Get the legend size, calculate new window width and change the figure size.
    legWidth = leg.get_window_extent().width
    winWidthNew = w*dpi+legWidth
    fig.set_size_inches(winWidthNew/dpi,h)
    
    # Adjust the window size to fit the figure.
    mgr = plt.get_current_fig_manager()
    mgr.window.wm_geometry("%ix%i"%(winWidthNew,mgr.window.winfo_height()))
    
    # Rescale the ax to keep its original size.
    factor = w*dpi/winWidthNew
    x0 = xlocs[0]*factor
    x1 = xlocs[1]*factor
    width = box.width*factor
    ax.set_position([x0,ylocs[0],x1-x0,ylocs[1]-ylocs[0]])
    
    plt.draw()
    

提交回复
热议问题