Skip to content

Commit 6970023

Browse files
authored
Merge pull request matplotlib#18646 from anntzer/figure
Support activating figures with plt.figure(figure_instance).
2 parents dd15dc0 + dca3bc4 commit 6970023

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

lib/matplotlib/pyplot.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -657,7 +657,7 @@ def figure(num=None, # autoincrement if None, else integer from 1-N
657657
658658
Parameters
659659
----------
660-
num : int or str, optional
660+
num : int or str or `.Figure`, optional
661661
A unique identifier for the figure.
662662
663663
If a figure with that identifier already exists, this figure is made
@@ -728,6 +728,11 @@ def figure(num=None, # autoincrement if None, else integer from 1-N
728728
`~matplotlib.rcParams` defines the default values, which can be modified
729729
in the matplotlibrc file.
730730
"""
731+
if isinstance(num, Figure):
732+
if num.canvas.manager is None:
733+
raise ValueError("The passed figure is not managed by pyplot")
734+
_pylab_helpers.Gcf.set_active(num.canvas.manager)
735+
return num
731736

732737
allnums = get_fignums()
733738
next_num = max(allnums) + 1 if allnums else 1
@@ -1055,9 +1060,7 @@ def sca(ax):
10551060
"""
10561061
Set the current Axes to *ax* and the current Figure to the parent of *ax*.
10571062
"""
1058-
if not hasattr(ax.figure.canvas, "manager"):
1059-
raise ValueError("Axes parent figure is not managed by pyplot")
1060-
_pylab_helpers.Gcf.set_active(ax.figure.canvas.manager)
1063+
figure(ax.figure)
10611064
ax.figure.sca(ax)
10621065

10631066

lib/matplotlib/tests/test_figure.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from matplotlib import cbook, rcParams
1111
from matplotlib.testing.decorators import image_comparison, check_figures_equal
1212
from matplotlib.axes import Axes
13+
from matplotlib.figure import Figure
1314
from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter
1415
import matplotlib.pyplot as plt
1516
import matplotlib.dates as mdates
@@ -60,10 +61,9 @@ def test_align_labels():
6061

6162

6263
def test_figure_label():
63-
# pyplot figure creation, selection and closing with figure label and
64-
# number
64+
# pyplot figure creation, selection, and closing with label/number/instance
6565
plt.close('all')
66-
plt.figure('today')
66+
fig_today = plt.figure('today')
6767
plt.figure(3)
6868
plt.figure('tomorrow')
6969
plt.figure()
@@ -78,6 +78,10 @@ def test_figure_label():
7878
plt.close('tomorrow')
7979
assert plt.get_fignums() == [0, 1]
8080
assert plt.get_figlabels() == ['', 'today']
81+
plt.figure(fig_today)
82+
assert plt.gcf() == fig_today
83+
with pytest.raises(ValueError):
84+
plt.figure(Figure())
8185

8286

8387
def test_fignum_exists():

0 commit comments

Comments
 (0)