Skip to content

[Bug]: Stackplot in SubFigure raises when drawing Legend #30158

Open
@szethh

Description

@szethh

Bug summary

When using subfigures, calling fig.legend() (on the main/root figure) after having drawn a stackplot (ax.stackplot) results in the following error:

RuntimeError: Can not put single artist in more than one figure

Code for reproduction

I copied the code from the stackplot example from the docs, then repeated it in a loop:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as mticker

year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population_by_continent = {
    "Africa": [0.228, 0.284, 0.365, 0.477, 0.631, 0.814, 1.044, 1.275],
    "the Americas": [0.340, 0.425, 0.519, 0.619, 0.727, 0.840, 0.943, 1.006],
    "Asia": [1.394, 1.686, 2.120, 2.625, 3.202, 3.714, 4.169, 4.560],
    "Europe": [0.220, 0.253, 0.276, 0.295, 0.310, 0.303, 0.294, 0.293],
    "Oceania": [0.012, 0.015, 0.019, 0.022, 0.026, 0.031, 0.036, 0.039],
}

fig = plt.figure()
subfigs = fig.subfigures(nrows=1, ncols=2)

for _fig in subfigs:
    axs = _fig.subplots(nrows=2, ncols=1, squeeze=False)[0]

    for ax in axs:
        ax.stackplot(
            year,
            population_by_continent.values(),
            labels=population_by_continent.keys(),
            alpha=0.8,
        )
        ax.legend(loc="upper left", reverse=True)
        ax.set_title("World population")
        ax.set_xlabel("Year")
        ax.set_ylabel("Number of people (billions)")
        # add tick at every 200 million people
        ax.yaxis.set_minor_locator(mticker.MultipleLocator(0.2))

fig.legend(loc="upper right", bbox_to_anchor=(1.1, 1)) # error!

Actual outcome

An exception is raised

Expected outcome

A legend is drawn. If in the provided example ax.stackplot is replaced by another plotting function (i.e. ax.plot, ax.scatter...) the error does not happen.

I have also tried:

  • fig.legend(handles, labels): Passing a list of artist/labels to .legend() causes the same error
  • subfigures[0].legend(): works, but obviously only prints artists present in said subfigure, not others.

Additional information

No response

Operating system

No response

Matplotlib Version

3.10.0

Matplotlib Backend

No response

Python version

No response

Jupyter version

No response

Installation

None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions