Search code examples
matplotliblegendfigure

matplotlib: Figure Legend with mode="expand" problem


I'm trying to use mode="expand" when defining a fig.legend().

I'm wanting it to expand to the xaxis extents which I am retrieving using ax.get_position().

I get 2 problems:

  1. It aligns correctly on LHS but for some reason it overshoots on the RHS.
  2. The 'upper center' of the legend does not align with upper center of my 4-tuple bbox. I have to manually fudge the numbers to make it do so.

See code below. (Matplotlib 3.1.0; Python 3.7; Numpy 1.16.4)

import matplotlib
import numpy as np

fig, ax = plt.subplots()
x = np.linspace(-2*np.pi,2*np.pi,100)
ax.plot(x,np.sin(x), label='sine')
ax.plot(x,np.cos(x), label='cos')
ax.plot(x,np.arctan(x), label='arctan')

axbox = ax.get_position()    

fig.legend(loc='upper center', bbox_to_anchor=(axbox.x0, axbox.y0, axbox.x1, axbox.y0), 
           bbox_transform=fig.transFigure, ncol=3, title='fig leg 3 expand', 
           prop={'size': 'medium'}, borderaxespad=0, mode="expand",
           )

resulting plot


Solution

  • In this case, I think we can change the transform reference to the axis and set the xy value to the range from 0 to 1. Does this fit your intent, I was not sure about LHS and RHS.

    fig.legend(loc='upper center', bbox_to_anchor=(0,0,1,0.15), 
               bbox_transform=ax.transAxes, ncol=3, title='fig leg 3 expand', 
               prop={'size': 'medium'}, borderaxespad=0, mode='expand',
               )
    

    enter image description here