Skip to content

Commit 8b018e4

Browse files
authored
get renderer fcn (#113)
* test get renderer fcn * fix restore_backend * add os name * move restore_backend to init * add test_set_size * more info on size * device_pixel_ratio * dpi=1000 * use finally * move and fix fcns
1 parent 73bca9d commit 8b018e4

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed

mplotutils/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from .cartopy_utils import *
99
from .colormaps import *
1010
from .map_layout import set_map_layout
11+
from .mpl import _get_renderer
1112
from .xrcompat import *
1213

1314
autodraw(True)

mplotutils/mpl.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import matplotlib
2+
3+
4+
def _get_renderer(fig):
5+
6+
if hasattr(fig.canvas, "get_renderer"):
7+
return fig.canvas.get_renderer()
8+
elif hasattr(fig, "_get_renderer"):
9+
return fig._get_renderer()
10+
11+
backend = matplotlib.get_backend()
12+
13+
raise AttributeError(
14+
f"Could not find a renderer for the '{backend}' backend. Please raise an issue"
15+
)

mplotutils/tests/__init__.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import contextlib
22

3+
import matplotlib
34
import matplotlib.pyplot as plt
5+
import pytest
46

57

68
@contextlib.contextmanager
@@ -21,3 +23,30 @@ def subplots_context(*args, **kwargs):
2123
yield fig, axs
2224
finally:
2325
plt.close(fig)
26+
27+
28+
@contextlib.contextmanager
29+
def restore_backend(backend):
30+
31+
current_backend = plt.get_backend()
32+
33+
try:
34+
_set_backend(backend)
35+
yield
36+
finally:
37+
plt.switch_backend(current_backend)
38+
39+
40+
def _set_backend(backend):
41+
42+
# WebAgg requires tornado, but this is only checked at runtime
43+
if backend == "WebAgg":
44+
try:
45+
import tornado # noqa: F401
46+
except ImportError:
47+
pytest.skip(backend)
48+
49+
try:
50+
matplotlib.use(backend)
51+
except ImportError:
52+
pytest.skip(backend)

mplotutils/tests/test_get_renderer.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import matplotlib
2+
import pytest
3+
4+
from mplotutils import _get_renderer
5+
6+
from . import figure_context, restore_backend
7+
8+
9+
@pytest.mark.parametrize("backend", matplotlib.rcsetup.all_backends)
10+
def test_get_renderer(backend):
11+
12+
with restore_backend(backend):
13+
14+
with figure_context() as f:
15+
_get_renderer(f)

0 commit comments

Comments
 (0)