Skip to content

Commit

Permalink
plt.gca() no longer accepts kwargs (pydata#5450)
Browse files Browse the repository at this point in the history
* plt.gca() no longer accepts kwargs

* use gcf unconditionally
  • Loading branch information
mathause authored Jun 9, 2021
1 parent e87d65b commit 136d654
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
17 changes: 16 additions & 1 deletion xarray/plot/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,11 +441,26 @@ def get_axis(figsize=None, size=None, aspect=None, ax=None, **kwargs):
raise ValueError("cannot use subplot_kws with existing ax")

if ax is None:
ax = plt.gca(**kwargs)
ax = _maybe_gca(**kwargs)

return ax


def _maybe_gca(**kwargs):

import matplotlib.pyplot as plt

# can call gcf unconditionally: either it exists or would be created by plt.axes
f = plt.gcf()

# only call gca if an active axes exists
if f.axes:
# can not pass kwargs to active axes
return plt.gca()

return plt.axes(**kwargs)


def label_from_attrs(da, extra=""):
"""Makes informative labels if variable metadata (attrs) follows
CF conventions."""
Expand Down
29 changes: 29 additions & 0 deletions xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
_build_discrete_cmap,
_color_palette,
_determine_cmap_params,
_maybe_gca,
get_axis,
label_from_attrs,
)
Expand Down Expand Up @@ -2777,3 +2778,31 @@ def test_get_axis_cartopy():
with figure_context():
ax = get_axis(**kwargs)
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot)


@requires_matplotlib
def test_maybe_gca():

with figure_context():
ax = _maybe_gca(aspect=1)

assert isinstance(ax, mpl.axes.Axes)
assert ax.get_aspect() == 1

with figure_context():

# create figure without axes
plt.figure()
ax = _maybe_gca(aspect=1)

assert isinstance(ax, mpl.axes.Axes)
assert ax.get_aspect() == 1

with figure_context():
existing_axes = plt.axes()
ax = _maybe_gca(aspect=1)

# re-uses the existing axes
assert existing_axes == ax
# kwargs are ignored when reusing axes
assert ax.get_aspect() == "auto"

0 comments on commit 136d654

Please sign in to comment.