Skip to content

Commit 484b2bf

Browse files
authored
ensure correct gca (#128)
1 parent 72e5393 commit 484b2bf

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

mplotutils/mpl.py

+15
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,18 @@ def _get_renderer(fig):
1313
raise AttributeError(
1414
f"Could not find a renderer for the '{backend}' backend. Please raise an issue"
1515
)
16+
17+
18+
def _maybe_gca(**kwargs):
19+
20+
import matplotlib.pyplot as plt
21+
22+
# can call gcf unconditionally: either it exists or would be created by plt.axes
23+
f = plt.gcf()
24+
25+
# only call gca if an active axes exists
26+
if f.axes:
27+
# can not pass kwargs to active axes
28+
return plt.gca()
29+
30+
return plt.axes(**kwargs)

mplotutils/tests/test_maybe_gca.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import matplotlib as mpl
2+
import matplotlib.pyplot as plt
3+
4+
from mplotutils.mpl import _maybe_gca
5+
6+
from . import figure_context
7+
8+
9+
def test_maybe_gca():
10+
11+
with figure_context():
12+
ax = _maybe_gca(aspect=1)
13+
14+
assert isinstance(ax, mpl.axes.Axes)
15+
assert ax.get_aspect() == 1
16+
17+
with figure_context():
18+
ax = _maybe_gca(aspect=1)
19+
20+
assert isinstance(ax, mpl.axes.Axes)
21+
assert ax.get_aspect() == 1
22+
23+
with figure_context():
24+
existing_axes = plt.axes()
25+
ax = _maybe_gca(aspect=1)
26+
27+
# re-uses the existing axes
28+
assert existing_axes == ax
29+
# kwargs are ignored when reusing axes
30+
assert ax.get_aspect() == "auto"

0 commit comments

Comments
 (0)