pylab.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """Implementation of magic functions for matplotlib/pylab support.
  2. """
  3. from __future__ import print_function
  4. #-----------------------------------------------------------------------------
  5. # Copyright (c) 2012 The IPython Development Team.
  6. #
  7. # Distributed under the terms of the Modified BSD License.
  8. #
  9. # The full license is in the file COPYING.txt, distributed with this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. # Our own packages
  15. from traitlets.config.application import Application
  16. from IPython.core import magic_arguments
  17. from IPython.core.magic import Magics, magics_class, line_magic
  18. from IPython.testing.skipdoctest import skip_doctest
  19. from warnings import warn
  20. from IPython.core.pylabtools import backends
  21. #-----------------------------------------------------------------------------
  22. # Magic implementation classes
  23. #-----------------------------------------------------------------------------
  24. magic_gui_arg = magic_arguments.argument(
  25. 'gui', nargs='?',
  26. help="""Name of the matplotlib backend to use %s.
  27. If given, the corresponding matplotlib backend is used,
  28. otherwise it will be matplotlib's default
  29. (which you can set in your matplotlib config file).
  30. """ % str(tuple(sorted(backends.keys())))
  31. )
  32. @magics_class
  33. class PylabMagics(Magics):
  34. """Magics related to matplotlib's pylab support"""
  35. @skip_doctest
  36. @line_magic
  37. @magic_arguments.magic_arguments()
  38. @magic_arguments.argument('-l', '--list', action='store_true',
  39. help='Show available matplotlib backends')
  40. @magic_gui_arg
  41. def matplotlib(self, line=''):
  42. """Set up matplotlib to work interactively.
  43. This function lets you activate matplotlib interactive support
  44. at any point during an IPython session. It does not import anything
  45. into the interactive namespace.
  46. If you are using the inline matplotlib backend in the IPython Notebook
  47. you can set which figure formats are enabled using the following::
  48. In [1]: from IPython.display import set_matplotlib_formats
  49. In [2]: set_matplotlib_formats('pdf', 'svg')
  50. The default for inline figures sets `bbox_inches` to 'tight'. This can
  51. cause discrepancies between the displayed image and the identical
  52. image created using `savefig`. This behavior can be disabled using the
  53. `%config` magic::
  54. In [3]: %config InlineBackend.print_figure_kwargs = {'bbox_inches':None}
  55. In addition, see the docstring of
  56. `IPython.display.set_matplotlib_formats` and
  57. `IPython.display.set_matplotlib_close` for more information on
  58. changing additional behaviors of the inline backend.
  59. Examples
  60. --------
  61. To enable the inline backend for usage with the IPython Notebook::
  62. In [1]: %matplotlib inline
  63. In this case, where the matplotlib default is TkAgg::
  64. In [2]: %matplotlib
  65. Using matplotlib backend: TkAgg
  66. But you can explicitly request a different GUI backend::
  67. In [3]: %matplotlib qt
  68. You can list the available backends using the -l/--list option::
  69. In [4]: %matplotlib --list
  70. Available matplotlib backends: ['osx', 'qt4', 'qt5', 'gtk3', 'notebook', 'wx', 'qt', 'nbagg',
  71. 'gtk', 'tk', 'inline']
  72. """
  73. args = magic_arguments.parse_argstring(self.matplotlib, line)
  74. if args.list:
  75. backends_list = list(backends.keys())
  76. print("Available matplotlib backends: %s" % backends_list)
  77. else:
  78. gui, backend = self.shell.enable_matplotlib(args.gui)
  79. self._show_matplotlib_backend(args.gui, backend)
  80. @skip_doctest
  81. @line_magic
  82. @magic_arguments.magic_arguments()
  83. @magic_arguments.argument(
  84. '--no-import-all', action='store_true', default=None,
  85. help="""Prevent IPython from performing ``import *`` into the interactive namespace.
  86. You can govern the default behavior of this flag with the
  87. InteractiveShellApp.pylab_import_all configurable.
  88. """
  89. )
  90. @magic_gui_arg
  91. def pylab(self, line=''):
  92. """Load numpy and matplotlib to work interactively.
  93. This function lets you activate pylab (matplotlib, numpy and
  94. interactive support) at any point during an IPython session.
  95. %pylab makes the following imports::
  96. import numpy
  97. import matplotlib
  98. from matplotlib import pylab, mlab, pyplot
  99. np = numpy
  100. plt = pyplot
  101. from IPython.display import display
  102. from IPython.core.pylabtools import figsize, getfigs
  103. from pylab import *
  104. from numpy import *
  105. If you pass `--no-import-all`, the last two `*` imports will be excluded.
  106. See the %matplotlib magic for more details about activating matplotlib
  107. without affecting the interactive namespace.
  108. """
  109. args = magic_arguments.parse_argstring(self.pylab, line)
  110. if args.no_import_all is None:
  111. # get default from Application
  112. if Application.initialized():
  113. app = Application.instance()
  114. try:
  115. import_all = app.pylab_import_all
  116. except AttributeError:
  117. import_all = True
  118. else:
  119. # nothing specified, no app - default True
  120. import_all = True
  121. else:
  122. # invert no-import flag
  123. import_all = not args.no_import_all
  124. gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
  125. self._show_matplotlib_backend(args.gui, backend)
  126. print ("Populating the interactive namespace from numpy and matplotlib")
  127. if clobbered:
  128. warn("pylab import has clobbered these variables: %s" % clobbered +
  129. "\n`%matplotlib` prevents importing * from pylab and numpy"
  130. )
  131. def _show_matplotlib_backend(self, gui, backend):
  132. """show matplotlib message backend message"""
  133. if not gui or gui == 'auto':
  134. print("Using matplotlib backend: %s" % backend)