Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mplotutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from .cartopy_utils import *
from .colormaps import *
from .map_layout import set_map_layout
from .mpl import _get_renderer
from .xrcompat import *

autodraw(True)
Expand Down
15 changes: 15 additions & 0 deletions mplotutils/mpl.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import matplotlib


def _get_renderer(fig):

if hasattr(fig.canvas, "get_renderer"):
return fig.canvas.get_renderer()
elif hasattr(fig, "_get_renderer"):
return fig._get_renderer()

backend = matplotlib.get_backend()

raise AttributeError(
f"Could not find a renderer for the '{backend}' backend. Please raise an issue"
)
29 changes: 29 additions & 0 deletions mplotutils/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import contextlib

import matplotlib
import matplotlib.pyplot as plt
import pytest


@contextlib.contextmanager
Expand All @@ -21,3 +23,30 @@ def subplots_context(*args, **kwargs):
yield fig, axs
finally:
plt.close(fig)


@contextlib.contextmanager
def restore_backend(backend):

current_backend = plt.get_backend()

try:
_set_backend(backend)
yield
finally:
plt.switch_backend(current_backend)


def _set_backend(backend):

# WebAgg requires tornado, but this is only checked at runtime
if backend == "WebAgg":
try:
import tornado # noqa: F401
except ImportError:
pytest.skip(backend)

try:
matplotlib.use(backend)
except ImportError:
pytest.skip(backend)
15 changes: 15 additions & 0 deletions mplotutils/tests/test_get_renderer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import matplotlib
import pytest

from mplotutils import _get_renderer

from . import figure_context, restore_backend


@pytest.mark.parametrize("backend", matplotlib.rcsetup.all_backends)
def test_get_renderer(backend):

with restore_backend(backend):

with figure_context() as f:
_get_renderer(f)