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