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()
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()