backend_inline.py 11 KB

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