I want to add a centered, common legend below a figure that has been modelled on the answer to an old question.
To do this, I try first make room for the legend with fig.subplots_adjust(bottom=0.3)
and then add the legend. But subplots_adjust()
doesn't seem to do anything. This I presume results in the legend being hidden behind the subplots. (The legend shows up just fine if I set loc="upper right"
.)
To be clear, I'm not married to the idea of using subplots_adjust()
. I just want to add a common legend that is centered below this figure.
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(constrained_layout=True)
fig.suptitle('Figure title')
x = np.arange(3)
width = 0.25
subfigs = fig.subfigures(nrows=3, ncols=1)
for row, subfig in enumerate(subfigs):
subfig.suptitle(f'Subfigure title {row}')
axs = subfig.subplots(nrows=1, ncols=2)
for col, ax in enumerate(axs):
ax.bar(x, 2 * (x + 0.5), width, label="One")
ax.bar(x + width, 3 * (x + 0.5), width, label="Two")
ax.set_title(f'Plot title {col}')
fig.subplots_adjust(bottom=0.5) # Doesn't seem to do anything
handles, labels = axs[0].get_legend_handles_labels()
fig.legend(handles, labels, ncol=len(handles), loc='lower center')
fig.show()