API: Raise ValueError in subplots if num refers to existing figure by Aaratrika-Shelly · Pull Request #31230 · matplotlib/matplotlib · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions doc/api/next_api_changes/behavior/31223-AS.rst
25 changes: 25 additions & 0 deletions lib/matplotlib/pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,25 @@ def fignum_exists(num: int | str) -> bool:
)


def _raise_if_figure_exists(num, func_name, clear=False):
"""
Raise a ValueError if the figure *num* already exists.
"""
if num is not None and not clear:
if isinstance(num, FigureBase):
raise ValueError(
f"num {num!r} cannot be a FigureBase instance. "
f"plt.{func_name}() is for creating new figures. "
f"To add to an existing figure, use fig.{func_name}() "
"instead.")

if fignum_exists(num):
raise ValueError(
f"Figure {num!r} already exists. Use plt.figure({num!r}) "
f"to get it or plt.close({num!r}) to close it. "
f"Alternatively, pass 'clear=True' to {func_name}().")


def get_fignums() -> list[int]:
"""Return a list of existing figure numbers."""
return sorted(_pylab_helpers.Gcf.figs)
Expand Down Expand Up @@ -1856,6 +1875,9 @@ def subplots(
fig, ax = plt.subplots(num=10, clear=True)

"""
num = fig_kw.get('num')
_raise_if_figure_exists(fig_kw.get('num'), "subplots", fig_kw.get('clear'))

fig = figure(**fig_kw)
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey,
squeeze=squeeze, subplot_kw=subplot_kw,
Expand Down Expand Up @@ -2029,6 +2051,9 @@ def subplot_mosaic(
total layout.

"""
num = fig_kw.get('num')
_raise_if_figure_exists(fig_kw.get('num'), "subplot_mosaic", fig_kw.get('clear'))

fig = figure(**fig_kw)
ax_dict = fig.subplot_mosaic( # type: ignore[misc]
mosaic, # type: ignore[arg-type]
Expand Down
39 changes: 39 additions & 0 deletions lib/matplotlib/tests/test_pyplot.py
Loading