Skip to content

Commit 136d654

Browse files
authored
plt.gca() no longer accepts kwargs (#5450)
* plt.gca() no longer accepts kwargs * use gcf unconditionally
1 parent e87d65b commit 136d654

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

xarray/plot/utils.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,11 +441,26 @@ def get_axis(figsize=None, size=None, aspect=None, ax=None, **kwargs):
441441
raise ValueError("cannot use subplot_kws with existing ax")
442442

443443
if ax is None:
444-
ax = plt.gca(**kwargs)
444+
ax = _maybe_gca(**kwargs)
445445

446446
return ax
447447

448448

449+
def _maybe_gca(**kwargs):
450+
451+
import matplotlib.pyplot as plt
452+
453+
# can call gcf unconditionally: either it exists or would be created by plt.axes
454+
f = plt.gcf()
455+
456+
# only call gca if an active axes exists
457+
if f.axes:
458+
# can not pass kwargs to active axes
459+
return plt.gca()
460+
461+
return plt.axes(**kwargs)
462+
463+
449464
def label_from_attrs(da, extra=""):
450465
"""Makes informative labels if variable metadata (attrs) follows
451466
CF conventions."""

xarray/tests/test_plot.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
_build_discrete_cmap,
1818
_color_palette,
1919
_determine_cmap_params,
20+
_maybe_gca,
2021
get_axis,
2122
label_from_attrs,
2223
)
@@ -2777,3 +2778,31 @@ def test_get_axis_cartopy():
27772778
with figure_context():
27782779
ax = get_axis(**kwargs)
27792780
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot)
2781+
2782+
2783+
@requires_matplotlib
2784+
def test_maybe_gca():
2785+
2786+
with figure_context():
2787+
ax = _maybe_gca(aspect=1)
2788+
2789+
assert isinstance(ax, mpl.axes.Axes)
2790+
assert ax.get_aspect() == 1
2791+
2792+
with figure_context():
2793+
2794+
# create figure without axes
2795+
plt.figure()
2796+
ax = _maybe_gca(aspect=1)
2797+
2798+
assert isinstance(ax, mpl.axes.Axes)
2799+
assert ax.get_aspect() == 1
2800+
2801+
with figure_context():
2802+
existing_axes = plt.axes()
2803+
ax = _maybe_gca(aspect=1)
2804+
2805+
# re-uses the existing axes
2806+
assert existing_axes == ax
2807+
# kwargs are ignored when reusing axes
2808+
assert ax.get_aspect() == "auto"

0 commit comments

Comments
 (0)