8000 [Bug]: subfigures messes up with fig.legend zorder · Issue #22011 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content
[Bug]: subfigures messes up with fig.legend zorder #22011
Closed
@cgadal

Description

@cgadal

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:
subfigures_figlegend2
With ax.set_facecolor('none') and subfig.set_facecolor('none') not commented, i.e transparent backgrounds:

subfigures_figlegend

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

subplots_figlegend

Additional information

  • This does not happen for ax.legend() and subfig.legend().

Operating system

Ubuntu 20

Matplotlib Version

3.5.0

Matplotlib Backend

QtAgg

Python version

3.8.10

Jupyter version

No response

Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Labels

    Difficulty: Mediumhttps://matplotlib.org/devdocs/devel/contribute.html#good-first-issuesGood first issueOpen a pull request against these issues if there are no active ones!topic: figures and subfigures

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0