diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 18a750c9f46d..bf87c9c43796 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -1595,6 +1595,45 @@ def __init__(self, figure): self.toolbar = None # NavigationToolbar2 will set me self._is_idle_drawing = False + def _repr_html_(self): + # Defer to IPython to handle html output if possible + if 'IPython' in sys.modules: + import IPython + ip = IPython.get_ipython() + # Check whether %matplotlib was run. Is there a better way? + ib_list = [c for c in ip.configurables + if 'InlineBackend' in type(c).__name__] + if ib_list: + return + + fmt = self.get_default_filetype() + + kw = { + "format":fmt, + "facecolor":self.figure.get_facecolor(), + "edgecolor":self.figure.get_edgecolor(), + "dpi":self.figure.dpi, + "bbox_inches":self.figure.bbox_inches + } + + bytes_io = io.BytesIO() + self.print_figure(bytes_io, **kw) + raw_bytes = bytes_io.getvalue() + + from base64 import b64encode + data = b64encode(raw_bytes).decode() + + if fmt == 'svg': + return raw_bytes.decode() + elif fmt == 'png': + return f'' + elif fmt == 'pdf': + w, h = self.figure.get_size_inches() + w, h = w * self.figure.dpi, h * self.figure.dpi + return f'' + elif fmt == 'jpg': + return f'' + @classmethod @functools.lru_cache() def _fix_ipython_backend2gui(cls): diff --git a/lib/matplotlib/backends/backend_webagg.py b/lib/matplotlib/backends/backend_webagg.py index cd5ada8cd073..b7b2601c948a 100644 --- a/lib/matplotlib/backends/backend_webagg.py +++ b/lib/matplotlib/backends/backend_webagg.py @@ -51,6 +51,9 @@ def run(self): class FigureCanvasWebAgg(core.FigureCanvasWebAggCore): _timer_cls = TimerTornado + def _repr_html_(self): + return ipython_inline_display(self.figure) + def show(self): # show the figure window global show # placates pyflakes: created by @_Backend.export below diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index b4141c8668f7..ea624eb1638f 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -369,11 +369,7 @@ def __init__(self, # use it, for some reason. def _repr_html_(self): - # We can't use "isinstance" here, because then we'd end up importing - # webagg unconditionally. - if 'WebAgg' in type(self.canvas).__name__: - from matplotlib.backends import backend_webagg - return backend_webagg.ipython_inline_display(self) + return self.canvas._repr_html_() def show(self, warn=True): """