@@ -532,3 +532,57 @@ def assert_same_signature(func1, func2):
532532
533533def test_setloglevel_signature ():
534534 assert_same_signature (plt .set_loglevel , mpl .set_loglevel )
535+
536+
537+ def test_subplots_reuse_existing_figure_error ():
538+ """Test interaction of plt.subplots(num=...) with existing figures."""
539+ # Create a figure with a specific number first.
540+ fig = plt .figure (1 )
541+
542+ # Case 1: Reusing without clear=True should raise ValueError
543+ with pytest .raises (ValueError , match = "already exists" ):
544+ plt .subplots (num = 1 )
545+
546+ # Case 2: Reusing WITH clear=True should work fine (no error)
547+ fig_new , axs = plt .subplots (num = 1 , clear = True )
548+ assert fig_new is fig
549+
550+ # Case 3: Test passing the actual Figure object (The "Narrow Check")
551+ with pytest .raises (ValueError , match = "cannot be a FigureBase instance" ):
552+ plt .subplots (num = fig )
553+
554+ plt .close (1 )
555+
556+
557+ def test_subplot_mosaic_reuse_existing_figure_error ():
558+ """Test that plt.subplot_mosaic raises ValueError when reusing a figure."""
559+ fig = plt .figure (2 )
560+
561+ # 1. Test passing the existing figure number
562+ with pytest .raises (ValueError , match = "already exists" ):
563+ plt .subplot_mosaic ([['A' ]], num = 2 )
564+
565+ # 2. Test passing the actual Figure object
566+ with pytest .raises (ValueError , match = "cannot be a FigureBase instance" ):
567+ plt .subplot_mosaic ([['A' ]], num = fig )
568+
569+ # 3. Test that clear=True allows reuse without error
570+ fig_new , axd = plt .subplot_mosaic ([['A' ]], num = 2 , clear = True )
571+ assert fig_new is fig
572+
573+ plt .close (2 )
574+
575+
576+ def test_subplots_error_on_double_call ():
577+ """
578+ Test that calling subplots twice on the same figure raises an error.
579+ This ensures that multiple calls to subplots on the same figure number
580+ without clear=True are correctly prohibited.
581+ """
582+
583+ plt .subplots (3 , 3 , num = 1 , gridspec_kw = {'left' : 0 , 'right' : 0.5 })
584+
585+ with pytest .raises (ValueError , match = "already exists" ):
586+ plt .subplots (num = 1 , gridspec_kw = {'left' : 0.5 , 'right' : 1 })
587+
588+ plt .close (1 )
0 commit comments