How to position and align a matplotlib figure legend?

后端 未结 2 1102
不思量自难忘°
不思量自难忘° 2020-12-14 02:21

I have a figure with two subplots as 2 rows and 1 column. I can add a nice looking figure legend with

fig.legend((l1, l2), [\'2011\', \'2012\'], loc=\"lower          


        
2条回答
  •  再見小時候
    2020-12-14 02:53

    In this case, you can either use axes for figure legend methods. In either case, bbox_to_anchor is the key. As you've already noticed bbox_to_anchor specifies a tuple of coordinates (or a box) to place the legend at. When you're using bbox_to_anchor think of the location kwarg as controlling the horizontal and vertical alignment.

    The difference is just whether the tuple of coordinates is interpreted as axes or figure coordinates.

    As an example of using a figure legend:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
    
    x = np.linspace(0, np.pi, 100)
    
    line1, = ax1.plot(x, np.cos(3*x), color='red')
    line2, = ax2.plot(x, np.sin(4*x), color='green')
    
    # The key to the position is bbox_to_anchor: Place it at x=0.5, y=0.5
    # in figure coordinates.
    # "center" is basically saying center horizontal alignment and 
    # center vertical alignment in this case
    fig.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0.5], 
               loc='center', ncol=2)
    
    plt.show()
    

    enter image description here

    As an example of using the axes method, try something like this:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
    
    x = np.linspace(0, np.pi, 100)
    
    line1, = ax1.plot(x, np.cos(3*x), color='red')
    line2, = ax2.plot(x, np.sin(4*x), color='green')
    
    # The key to the position is bbox_to_anchor: Place it at x=0.5, y=0
    # in axes coordinates.
    # "upper center" is basically saying center horizontal alignment and 
    # top vertical alignment in this case
    ax1.legend([line1, line2], ['yep', 'nope'], bbox_to_anchor=[0.5, 0], 
               loc='upper center', ncol=2, borderaxespad=0.25)
    
    plt.show()
    

    enter image description here

提交回复
热议问题