Closed
Description
Bug summary
When using subfigures, legends called with fig.legend()
are hidden behind the subfigure background and the axes background.
Code for reproduction
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.set_facecolor('none') # Comment this line
subfig.set_facecolor('none') # and this line to make the legend hidden behing the white backgrounds
l = fig.legend(handles=[l1, l2], loc='upper center', ncol=2)
plt.savefig('subfigures_figlegend.png', dpi=200)
plt.show()
Actual outcome
With ax.set_facecolor('none')
and subfig.set_facecolor('none')
commented:
With ax.set_facecolor('none')
and subfig.set_facecolor('none')
not commented, i.e transparent backgrounds:
Expected outcome
Legend should be on the top of the backgrounds, as produced when building the figure with 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)
plt.show()
Additional information
- This does not happen for
ax.legend()
andsubfig.legend()
.
Operating system
Ubuntu 20
Matplotlib Version
3.5.0
Matplotlib Backend
QtAgg
Python version
3.8.10
Jupyter version
No response
Installation
pip