@@ -1178,6 +1178,25 @@ def fignum_exists(num: int | str) -> bool:
11781178 )
11791179
11801180
1181+ def _raise_if_figure_exists (num , func_name , clear = False ):
1182+ """
1183+ Raise a ValueError if the figure *num* already exists.
1184+ """
1185+ if num is not None and not clear :
1186+ if isinstance (num , FigureBase ):
1187+ raise ValueError (
1188+ f"num { num !r} cannot be a FigureBase instance. "
1189+ f"plt.{ func_name } () is for creating new figures. "
1190+ f"To add to an existing figure, use fig.{ func_name } () "
1191+ "instead." )
1192+
1193+ if fignum_exists (num ):
1194+ raise ValueError (
1195+ f"Figure { num !r} already exists. Use plt.figure({ num !r} ) "
1196+ f"to get it or plt.close({ num !r} ) to close it. "
1197+ f"Alternatively, pass 'clear=True' to { func_name } ()." )
1198+
1199+
11811200def get_fignums () -> list [int ]:
11821201 """Return a list of existing figure numbers."""
11831202 return sorted (_pylab_helpers .Gcf .figs )
@@ -1856,6 +1875,9 @@ def subplots(
18561875 fig, ax = plt.subplots(num=10, clear=True)
18571876
18581877 """
1878+ num = fig_kw .get ('num' )
1879+ _raise_if_figure_exists (fig_kw .get ('num' ), "subplots" , fig_kw .get ('clear' ))
1880+
18591881 fig = figure (** fig_kw )
18601882 axs = fig .subplots (nrows = nrows , ncols = ncols , sharex = sharex , sharey = sharey ,
18611883 squeeze = squeeze , subplot_kw = subplot_kw ,
@@ -2029,6 +2051,9 @@ def subplot_mosaic(
20292051 total layout.
20302052
20312053 """
2054+ num = fig_kw .get ('num' )
2055+ _raise_if_figure_exists (fig_kw .get ('num' ), "subplot_mosaic" , fig_kw .get ('clear' ))
2056+
20322057 fig = figure (** fig_kw )
20332058 ax_dict = fig .subplot_mosaic ( # type: ignore[misc]
20342059 mosaic , # type: ignore[arg-type]
0 commit comments