I have a plot with 2 subplots, all sharing corresponding graphs, i.e. same label for same color. I want to have one legend over the top of the plots, extending over both subplots. Similar to the following code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1,1,1000)
y1 = x
y2 = 0.1*x**2
y3 = x**3
y4 = x**4
y5 = x**5
fig, grid = plt.subplots(1,2,sharex="col", sharey="row")
fig.subplots_adjust(wspace=0, hspace=0)
grid[0].plot(x,y1, label='1')
grid[0].plot(x,y2, label='2')
grid[0].plot(x,y3, label='3')
grid[0].plot(x,y4, label='4')
grid[0].plot(x,y5, label='5')
grid[1].plot(x,y1, label='1')
grid[0].legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=5, borderaxespad=0.)
plt.show()
This example looks almost good. The only problem is that the legend extends from the beginning of the first plot and ends over the middle of the second one. However, I would like the legend to extend over both plots. How can I do that?
Note: Original problem uses 2x3 grid (2 rows, 3 columns).