EDIT: This has been fixed in last versions of matplotlib here
Disclaimer: I am aware that using subfigures is irrelevant in this simple example, the latter is used only to show my problem: I want to be able to use fig.legend() with fig.subfigures1.
I am currently discovering the new subfigure module of matplotlib. I noticed that figure legends created using fig.legend() does not show up when the main figure contains subfigures:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(1, 10, 10)
y1 = x
y2 = -x
fig = plt.figure(constrained_layout=True)
subfigs = fig.subfigures(nrows=2, ncols=1)
for subfig in subfigs:
axarr = subfig.subplots(1, 2)
for ax in axarr.flatten():
l1, = ax.plot(x, y1, label='line1')
l2, = ax.plot(x, y2, label='line2')
#
ax.legend()
# subfig.legend(handles=[l1, l2], loc='upper center', ncol=2)
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subfigures_figlegend.png', dpi=200)

Note how that figure legend is absent. For comparison, note that is shows up when using only plt.subplots:
fig, axarr = plt.subplots(2, 2, constrained_layout=True)
for ax in axarr.flatten():
l1, = ax.plot(x, y1, label='line1')
l2, = ax.plot(x, y2, label='line2')
#
ax.legend()
fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subplots_figlegend.png', dpi=200)

When I ran your code the legend was there, but it was behind and slightly above the plot, and then cut off when plt.savefig() is called. I was able to get it to work with the bbox_inches='tight' argument of plt.savefig() and the following to move the legend.
fig.legend(handles=[l1, l2], bbox_to_anchor=(0.7, 1.1), ncol=2)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With