backend_inline.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. """A matplotlib backend for publishing figures via display_data"""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the BSD 3-Clause License.
  4. import matplotlib
  5. from IPython.core.getipython import get_ipython
  6. from IPython.core.interactiveshell import InteractiveShell
  7. from IPython.core.pylabtools import select_figure_formats
  8. from IPython.display import display
  9. from matplotlib import colors
  10. from matplotlib._pylab_helpers import Gcf
  11. from matplotlib.backends import backend_agg
  12. from matplotlib.backends.backend_agg import FigureCanvasAgg
  13. from matplotlib.figure import Figure
  14. from .config import InlineBackend
  15. def new_figure_manager(num, *args, FigureClass=Figure, **kwargs):
  16. """
  17. Return a new figure manager for a new figure instance.
  18. This function is part of the API expected by Matplotlib backends.
  19. """
  20. return new_figure_manager_given_figure(num, FigureClass(*args, **kwargs))
  21. def new_figure_manager_given_figure(num, figure):
  22. """
  23. Return a new figure manager for a given figure instance.
  24. This function is part of the API expected by Matplotlib backends.
  25. """
  26. manager = backend_agg.new_figure_manager_given_figure(num, figure)
  27. # Hack: matplotlib FigureManager objects in interacive backends (at least
  28. # in some of them) monkeypatch the figure object and add a .show() method
  29. # to it. This applies the same monkeypatch in order to support user code
  30. # that might expect `.show()` to be part of the official API of figure
  31. # objects. For further reference:
  32. # https://github.com/ipython/ipython/issues/1612
  33. # https://github.com/matplotlib/matplotlib/issues/835
  34. if not hasattr(figure, "show"):
  35. # Queue up `figure` for display
  36. figure.show = lambda *a: display(
  37. figure, metadata=_fetch_figure_metadata(figure)
  38. )
  39. # If matplotlib was manually set to non-interactive mode, this function
  40. # should be a no-op (otherwise we'll generate duplicate plots, since a user
  41. # who set ioff() manually expects to make separate draw/show calls).
  42. if not matplotlib.is_interactive():
  43. return manager
  44. # ensure current figure will be drawn, and each subsequent call
  45. # of draw_if_interactive() moves the active figure to ensure it is
  46. # drawn last
  47. try:
  48. show._to_draw.remove(figure)
  49. except ValueError:
  50. # ensure it only appears in the draw list once
  51. pass
  52. # Queue up the figure for drawing in next show() call
  53. show._to_draw.append(figure)
  54. show._draw_called = True
  55. return manager
  56. def show(close=None, block=None):
  57. """Show all figures as SVG/PNG payloads sent to the IPython clients.
  58. Parameters
  59. ----------
  60. close : bool, optional
  61. If true, a ``plt.close('all')`` call is automatically issued after
  62. sending all the figures. If this is set, the figures will entirely
  63. removed from the internal list of figures.
  64. block : Not used.
  65. The `block` parameter is a Matplotlib experimental parameter.
  66. We accept it in the function signature for compatibility with other
  67. backends.
  68. """
  69. if close is None:
  70. close = InlineBackend.instance().close_figures
  71. try:
  72. for figure_manager in Gcf.get_all_fig_managers():
  73. display(
  74. figure_manager.canvas.figure,
  75. metadata=_fetch_figure_metadata(figure_manager.canvas.figure),
  76. )
  77. finally:
  78. show._to_draw = []
  79. # only call close('all') if any to close
  80. # close triggers gc.collect, which can be slow
  81. if close and Gcf.get_all_fig_managers():
  82. matplotlib.pyplot.close("all")
  83. # This flag will be reset by draw_if_interactive when called
  84. show._draw_called = False # type: ignore[attr-defined]
  85. # list of figures to draw when flush_figures is called
  86. show._to_draw = [] # type: ignore[attr-defined]
  87. def flush_figures():
  88. """Send all figures that changed
  89. This is meant to be called automatically and will call show() if, during
  90. prior code execution, there had been any calls to draw_if_interactive.
  91. This function is meant to be used as a post_execute callback in IPython,
  92. so user-caused errors are handled with showtraceback() instead of being
  93. allowed to raise. If this function is not called from within IPython,
  94. then these exceptions will raise.
  95. """
  96. if not show._draw_called:
  97. return
  98. try:
  99. if InlineBackend.instance().close_figures:
  100. # ignore the tracking, just draw and close all figures
  101. try:
  102. return show(True)
  103. except Exception as e:
  104. # safely show traceback if in IPython, else raise
  105. ip = get_ipython()
  106. if ip is None:
  107. raise e
  108. else:
  109. ip.showtraceback()
  110. return
  111. # exclude any figures that were closed:
  112. active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
  113. for fig in [fig for fig in show._to_draw if fig in active]:
  114. try:
  115. display(fig, metadata=_fetch_figure_metadata(fig))
  116. except Exception as e:
  117. # safely show traceback if in IPython, else raise
  118. ip = get_ipython()
  119. if ip is None:
  120. raise e
  121. else:
  122. ip.showtraceback()
  123. return
  124. finally:
  125. # clear flags for next round
  126. show._to_draw = []
  127. show._draw_called = False
  128. # Changes to matplotlib in version 1.2 requires a mpl backend to supply a default
  129. # figurecanvas. This is set here to a Agg canvas
  130. # See https://github.com/matplotlib/matplotlib/pull/1125
  131. FigureCanvas = FigureCanvasAgg
  132. def configure_inline_support(shell, backend):
  133. """Configure an IPython shell object for matplotlib use.
  134. Parameters
  135. ----------
  136. shell : InteractiveShell instance
  137. backend : matplotlib backend
  138. """
  139. # If using our svg payload backend, register the post-execution
  140. # function that will pick up the results for display. This can only be
  141. # done with access to the real shell object.
  142. cfg = InlineBackend.instance(parent=shell)
  143. cfg.shell = shell
  144. if cfg not in shell.configurables:
  145. shell.configurables.append(cfg)
  146. if backend in ("inline", "module://matplotlib_inline.backend_inline"):
  147. shell.events.register("post_execute", flush_figures)
  148. # Save rcParams that will be overwrittern
  149. shell._saved_rcParams = {}
  150. for k in cfg.rc:
  151. shell._saved_rcParams[k] = matplotlib.rcParams[k]
  152. # load inline_rc
  153. matplotlib.rcParams.update(cfg.rc)
  154. new_backend_name = "inline"
  155. else:
  156. try:
  157. shell.events.unregister("post_execute", flush_figures)
  158. except ValueError:
  159. pass
  160. if hasattr(shell, "_saved_rcParams"):
  161. matplotlib.rcParams.update(shell._saved_rcParams)
  162. del shell._saved_rcParams
  163. new_backend_name = "other"
  164. # only enable the formats once -> don't change the enabled formats (which the user may
  165. # has changed) when getting another "%matplotlib inline" call.
  166. # See https://github.com/ipython/ipykernel/issues/29
  167. cur_backend = getattr(configure_inline_support, "current_backend", "unset")
  168. if new_backend_name != cur_backend:
  169. # Setup the default figure format
  170. select_figure_formats(shell, cfg.figure_formats, **cfg.print_figure_kwargs)
  171. configure_inline_support.current_backend = new_backend_name
  172. def _enable_matplotlib_integration():
  173. """Enable extra IPython matplotlib integration when we are loaded as the matplotlib backend."""
  174. ip = get_ipython()
  175. import matplotlib
  176. if matplotlib.__version_info__ >= (3, 10):
  177. backend = matplotlib.get_backend(auto_select=False)
  178. else:
  179. backend = matplotlib.rcParams._get("backend")
  180. if ip and backend in ("inline", "module://matplotlib_inline.backend_inline"):
  181. from IPython.core.pylabtools import activate_matplotlib
  182. try:
  183. activate_matplotlib(backend)
  184. configure_inline_support(ip, backend)
  185. except (ImportError, AttributeError):
  186. # bugs may cause a circular import on Python 2
  187. def configure_once(*args):
  188. activate_matplotlib(backend)
  189. configure_inline_support(ip, backend)
  190. ip.events.unregister("post_run_cell", configure_once)
  191. ip.events.register("post_run_cell", configure_once)
  192. _enable_matplotlib_integration()
  193. def _fetch_figure_metadata(fig):
  194. """Get some metadata to help with displaying a figure."""
  195. # determine if a background is needed for legibility
  196. if _is_transparent(fig.get_facecolor()):
  197. # the background is transparent
  198. ticksLight = _is_light(
  199. [
  200. label.get_color()
  201. for axes in fig.axes
  202. for axis in (axes.xaxis, axes.yaxis)
  203. for label in axis.get_ticklabels()
  204. ]
  205. )
  206. if ticksLight.size and (ticksLight == ticksLight[0]).all():
  207. # there are one or more tick labels, all with the same lightness
  208. return {"needs_background": "dark" if ticksLight[0] else "light"}
  209. return None
  210. def _is_light(color):
  211. """Determines if a color (or each of a sequence of colors) is light (as
  212. opposed to dark). Based on ITU BT.601 luminance formula (see
  213. https://stackoverflow.com/a/596241)."""
  214. rgbaArr = colors.to_rgba_array(color)
  215. return rgbaArr[:, :3].dot((0.299, 0.587, 0.114)) > 0.5
  216. def _is_transparent(color):
  217. """Determine transparency from alpha."""
  218. rgba = colors.to_rgba(color)
  219. return rgba[3] < 0.5
  220. def set_matplotlib_formats(*formats, **kwargs):
  221. """Select figure formats for the inline backend. Optionally pass quality for JPEG.
  222. For example, this enables PNG and JPEG output with a JPEG quality of 90%::
  223. In [1]: set_matplotlib_formats('png', 'jpeg',
  224. pil_kwargs={'quality': 90})
  225. To set this in your notebook by `%config` magic::
  226. In [1]: %config InlineBackend.figure_formats = {'png', 'jpeg'}
  227. %config InlineBackend.print_figure_kwargs = \\
  228. {'pil_kwargs': {'quality' : 90}}
  229. To set this in your config files use the following::
  230. c.InlineBackend.figure_formats = {'png', 'jpeg'}
  231. c.InlineBackend.print_figure_kwargs.update({
  232. 'pil_kwargs': {'quality' : 90}
  233. })
  234. Parameters
  235. ----------
  236. *formats : strs
  237. One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
  238. **kwargs
  239. Keyword args will be relayed to ``figure.canvas.print_figure``.
  240. In addition, see the docstrings of `plt.savefig()`,
  241. `matplotlib.figure.Figure.savefig()`, `PIL.Image.Image.save()` and
  242. :ref:`Pillow Image file formats <handbook/image-file-formats>`.
  243. """
  244. # build kwargs, starting with InlineBackend config
  245. cfg = InlineBackend.instance()
  246. kw = {}
  247. kw.update(cfg.print_figure_kwargs)
  248. kw.update(**kwargs)
  249. shell = InteractiveShell.instance()
  250. select_figure_formats(shell, formats, **kw)
  251. def set_matplotlib_close(close=True):
  252. """Set whether the inline backend closes all figures automatically or not.
  253. By default, the inline backend used in the IPython Notebook will close all
  254. matplotlib figures automatically after each cell is run. This means that
  255. plots in different cells won't interfere. Sometimes, you may want to make
  256. a plot in one cell and then refine it in later cells. This can be accomplished
  257. by::
  258. In [1]: set_matplotlib_close(False)
  259. To set this in your config files use the following::
  260. c.InlineBackend.close_figures = False
  261. Parameters
  262. ----------
  263. close : bool
  264. Should all matplotlib figures be automatically closed after each cell is
  265. run?
  266. """
  267. cfg = InlineBackend.instance()
  268. cfg.close_figures = close