##// END OF EJS Templates
add `%matplotlib` and `shell.enable_matplotlib`...
MinRK -
Show More
@@ -55,7 +55,6 b' from IPython.core.macro import Macro'
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.pylabtools import pylab_activate
59 from IPython.core.prompts import PromptManager
58 from IPython.core.prompts import PromptManager
60 from IPython.lib.latextools import LaTeXTool
59 from IPython.lib.latextools import LaTeXTool
61 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
@@ -2832,6 +2831,51 b' class InteractiveShell(SingletonConfigurable):'
2832
2831
2833 def enable_gui(self, gui=None):
2832 def enable_gui(self, gui=None):
2834 raise NotImplementedError('Implement enable_gui in a subclass')
2833 raise NotImplementedError('Implement enable_gui in a subclass')
2834
2835 def enable_matplotlib(self, gui=None):
2836 """Enable interactive matplotlib and inline figure support.
2837
2838 This takes the following steps:
2839
2840 1. select the appropriate eventloop and matplotlib backend
2841 2. set up matplotlib for interactive use with that backend
2842 3. configure formatters for inline figure display
2843 4. enable the selected gui eventloop
2844
2845 Parameters
2846 ----------
2847 gui : optional, string
2848 If given, dictates the choice of matplotlib GUI backend to use
2849 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2850 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2851 matplotlib (as dictated by the matplotlib build-time options plus the
2852 user's matplotlibrc configuration file). Note that not all backends
2853 make sense in all contexts, for example a terminal ipython can't
2854 display figures inline.
2855 """
2856 from IPython.core import pylabtools as pt
2857 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2858
2859 if gui != 'inline':
2860 # If we have our first gui selection, store it
2861 if self.pylab_gui_select is None:
2862 self.pylab_gui_select = gui
2863 # Otherwise if they are different
2864 elif gui != self.pylab_gui_select:
2865 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2866 ' Using %s instead.' % (gui, self.pylab_gui_select))
2867 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2868
2869 pt.activate_matplotlib(backend)
2870 pt.configure_inline_support(self, backend)
2871
2872 # Now we must activate the gui pylab wants to use, and fix %run to take
2873 # plot updates into account
2874 self.enable_gui(gui)
2875 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2876 pt.mpl_runner(self.safe_execfile)
2877
2878 return gui, backend
2835
2879
2836 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2880 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2837 """Activate pylab support at runtime.
2881 """Activate pylab support at runtime.
@@ -2840,6 +2884,8 b' class InteractiveShell(SingletonConfigurable):'
2840 namespace all of numpy and pylab, and configures IPython to correctly
2884 namespace all of numpy and pylab, and configures IPython to correctly
2841 interact with the GUI event loop. The GUI backend to be used can be
2885 interact with the GUI event loop. The GUI backend to be used can be
2842 optionally selected with the optional ``gui`` argument.
2886 optionally selected with the optional ``gui`` argument.
2887
2888 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2843
2889
2844 Parameters
2890 Parameters
2845 ----------
2891 ----------
@@ -2851,38 +2897,29 b' class InteractiveShell(SingletonConfigurable):'
2851 user's matplotlibrc configuration file). Note that not all backends
2897 user's matplotlibrc configuration file). Note that not all backends
2852 make sense in all contexts, for example a terminal ipython can't
2898 make sense in all contexts, for example a terminal ipython can't
2853 display figures inline.
2899 display figures inline.
2900 import_all : optional, bool, default: True
2901 Whether to do `from numpy import *` and `from pylab import *`
2902 in addition to module imports.
2903 welcome_message : deprecated
2904 This argument is ignored, no welcome message will be displayed.
2854 """
2905 """
2855 from IPython.core.pylabtools import mpl_runner, backends
2906 from IPython.core.pylabtools import import_pylab
2907
2908 gui, backend = self.enable_matplotlib(gui)
2909
2856 # We want to prevent the loading of pylab to pollute the user's
2910 # We want to prevent the loading of pylab to pollute the user's
2857 # namespace as shown by the %who* magics, so we execute the activation
2911 # namespace as shown by the %who* magics, so we execute the activation
2858 # code in an empty namespace, and we update *both* user_ns and
2912 # code in an empty namespace, and we update *both* user_ns and
2859 # user_ns_hidden with this information.
2913 # user_ns_hidden with this information.
2860 ns = {}
2914 ns = {}
2861 try:
2915 import_pylab(ns, import_all)
2862 gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message)
2863 except KeyError:
2864 error("Backend '%s' not supported. Supported backends are: %s"
2865 % (gui, " ".join(sorted(backends.keys()))))
2866 return
2867 except ImportError:
2868 error("pylab mode doesn't work as matplotlib or its backend could not be imported." + \
2869 "\nIs it installed on the system?")
2870 return
2871 # warn about clobbered names
2916 # warn about clobbered names
2872 ignored = set(["__builtins__"])
2917 ignored = set(["__builtins__"])
2873 both = set(ns).intersection(self.user_ns).difference(ignored)
2918 both = set(ns).intersection(self.user_ns).difference(ignored)
2874 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2919 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2875 if clobbered:
2876 warn("pylab import has clobbered these variables: %s"
2877 "\n`%%pylab --no-import` prevents imports from pylab, numpy, etc." % clobbered
2878 )
2879 self.user_ns.update(ns)
2920 self.user_ns.update(ns)
2880 self.user_ns_hidden.update(ns)
2921 self.user_ns_hidden.update(ns)
2881 # Now we must activate the gui pylab wants to use, and fix %run to take
2922 return gui, backend, clobbered
2882 # plot updates into account
2883 self.enable_gui(gui)
2884 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2885 mpl_runner(self.safe_execfile)
2886
2923
2887 #-------------------------------------------------------------------------
2924 #-------------------------------------------------------------------------
2888 # Utilities
2925 # Utilities
@@ -17,23 +17,13 b' from IPython.config.application import Application'
17 from IPython.core import magic_arguments
17 from IPython.core import magic_arguments
18 from IPython.core.magic import Magics, magics_class, line_magic
18 from IPython.core.magic import Magics, magics_class, line_magic
19 from IPython.testing.skipdoctest import skip_doctest
19 from IPython.testing.skipdoctest import skip_doctest
20 from IPython.utils.warn import warn
20
21
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22 # Magic implementation classes
23 # Magic implementation classes
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
24
25
25 @magics_class
26 magic_gui_arg = magic_arguments.argument(
26 class PylabMagics(Magics):
27 """Magics related to matplotlib's pylab support"""
28
29 @skip_doctest
30 @line_magic
31 @magic_arguments.magic_arguments()
32 @magic_arguments.argument(
33 '--no-import', action='store_true', default=None,
34 help="""Prevent IPython from populating the namespace"""
35 )
36 @magic_arguments.argument(
37 'gui', nargs='?',
27 'gui', nargs='?',
38 help="""Name of the matplotlib backend to use
28 help="""Name of the matplotlib backend to use
39 ('qt', 'wx', 'gtk', 'osx', 'tk', 'inline', 'auto').
29 ('qt', 'wx', 'gtk', 'osx', 'tk', 'inline', 'auto').
@@ -41,18 +31,24 b' class PylabMagics(Magics):'
41 otherwise it will be matplotlib's default
31 otherwise it will be matplotlib's default
42 (which you can set in your matplotlib config file).
32 (which you can set in your matplotlib config file).
43 """
33 """
44 )
34 )
45 def pylab(self, line=''):
46 """Load numpy and matplotlib to work interactively.
47
48 %pylab [GUINAME]
49
35
50 This function lets you activate pylab (matplotlib, numpy and
51 interactive support) at any point during an IPython session.
52
53 It will import at the top level numpy as np, pyplot as plt, matplotlib,
54 pylab and mlab, as well as all names from numpy and pylab.
55
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_gui_arg
45 def matplotlib(self, line=''):
46 """Set up matplotlib to work interactively.
47
48 This function lets you activate matplotlib interactive support
49 at any point during an IPython session.
50 It does not import anything into the interactive namespace.
51
56 If you are using the inline matplotlib backend for embedded figures,
52 If you are using the inline matplotlib backend for embedded figures,
57 you can adjust its behavior via the %config magic::
53 you can adjust its behavior via the %config magic::
58
54
@@ -64,34 +60,59 b' class PylabMagics(Magics):'
64 # cells:
60 # cells:
65 In [2]: %config InlineBackend.close_figures = False
61 In [2]: %config InlineBackend.close_figures = False
66
62
67 Parameters
68 ----------
69 guiname : optional
70 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
71 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
72 used, otherwise matplotlib's default (which you can override in your
73 matplotlib config file) is used.
74
75 Examples
63 Examples
76 --------
64 --------
77 In this case, where the MPL default is TkAgg::
65 In this case, where the MPL default is TkAgg::
78
66
79 In [2]: %pylab
67 In [2]: %matplotlib
80
68 Using matplotlib backend: TkAgg
81 Welcome to pylab, a matplotlib-based Python environment.
82 Backend in use: TkAgg
83 For more information, type 'help(pylab)'.
84
69
85 But you can explicitly request a different backend::
70 But you can explicitly request a different backend::
86
71
87 In [3]: %pylab qt
72 In [3]: %matplotlib qt
73 """
74 args = magic_arguments.parse_argstring(self.matplotlib, line)
75 gui, backend = self.shell.enable_matplotlib(args.gui)
76 self._show_matplotlib_backend(args.gui, backend)
88
77
89 Welcome to pylab, a matplotlib-based Python environment.
78 @skip_doctest
90 Backend in use: Qt4Agg
79 @line_magic
91 For more information, type 'help(pylab)'.
80 @magic_arguments.magic_arguments()
81 @magic_arguments.argument(
82 '--no-import-all', action='store_true', default=None,
83 help="""Prevent IPython from performing ``import *`` into the interactive namespace.
84
85 The names that will still be added to the namespace if this flag is given::
86
87 numpy
88 matplotlib
89 np (numpy alias)
90 plt (matplotlib.pyplot alias)
91 pylab (from matplotlib)
92 pyplot (from matplotlib)
93 mlab (from matplotlib)
94 display (from IPython)
95 figsize (from IPython)
96 getfigs (from IPython)
97
98 You can govern the default behavior with the
99 InteractiveShellApp.pylab_import_all configurable.
100 """
101 )
102 @magic_gui_arg
103 def pylab(self, line=''):
104 """Load numpy and matplotlib to work interactively.
105
106 This function lets you activate pylab (matplotlib, numpy and
107 interactive support) at any point during an IPython session.
108
109 It will import at the top level numpy as np, pyplot as plt, matplotlib,
110 pylab and mlab, as well as all names from numpy and pylab.
111
112 See the %matplotlib magic for more details.
92 """
113 """
93 args = magic_arguments.parse_argstring(self.pylab, line)
114 args = magic_arguments.parse_argstring(self.pylab, line)
94 if args.no_import is None:
115 if args.no_import_all is None:
95 # get default from Application
116 # get default from Application
96 if Application.initialized():
117 if Application.initialized():
97 app = Application.instance()
118 app = Application.instance()
@@ -104,6 +125,17 b' class PylabMagics(Magics):'
104 import_all = True
125 import_all = True
105 else:
126 else:
106 # invert no-import flag
127 # invert no-import flag
107 import_all = not args.no_import
128 import_all = not args.no_import_all
108
129
109 self.shell.enable_pylab(args.gui, import_all=import_all, welcome_message=True)
130 gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
131 self._show_matplotlib_backend(args.gui, backend)
132 if clobbered:
133 warn("pylab import has clobbered these variables: %s" % clobbered +
134 "\n`%pylab --no-import-all` prevents importing * from pylab and numpy"
135 )
136
137 def _show_matplotlib_backend(self, gui, backend):
138 """show matplotlib message backend message"""
139 if not gui or gui == 'auto':
140 print ("using matplotlib backend: %s" % backend)
141
@@ -231,7 +231,7 b' def activate_matplotlib(backend):'
231
231
232 import matplotlib
232 import matplotlib
233 matplotlib.interactive(True)
233 matplotlib.interactive(True)
234
234
235 # Matplotlib had a bug where even switch_backend could not force
235 # Matplotlib had a bug where even switch_backend could not force
236 # the rcParam to update. This needs to be set *before* the module
236 # the rcParam to update. This needs to be set *before* the module
237 # magic of switch_backend().
237 # magic of switch_backend().
@@ -257,7 +257,6 b' def import_pylab(user_ns, import_all=True):'
257
257
258 Also imports a few names from IPython (figsize, display, getfigs)
258 Also imports a few names from IPython (figsize, display, getfigs)
259
259
260 The import_all parameter is included for backward compatibility, but ignored.
261 """
260 """
262
261
263 # Import numpy as np/pyplot as plt are conventions we're trying to
262 # Import numpy as np/pyplot as plt are conventions we're trying to
@@ -271,9 +270,10 b' def import_pylab(user_ns, import_all=True):'
271 )
270 )
272 exec s in user_ns
271 exec s in user_ns
273
272
274 s = ("from matplotlib.pylab import *\n"
273 if import_all:
275 "from numpy import *\n")
274 s = ("from matplotlib.pylab import *\n"
276 exec s in user_ns
275 "from numpy import *\n")
276 exec s in user_ns
277
277
278 # IPython symbols to add
278 # IPython symbols to add
279 user_ns['figsize'] = figsize
279 user_ns['figsize'] = figsize
@@ -283,7 +283,7 b' def import_pylab(user_ns, import_all=True):'
283 user_ns['getfigs'] = getfigs
283 user_ns['getfigs'] = getfigs
284
284
285
285
286 def configure_inline_support(shell, backend, user_ns=None):
286 def configure_inline_support(shell, backend):
287 """Configure an IPython shell object for matplotlib use.
287 """Configure an IPython shell object for matplotlib use.
288
288
289 Parameters
289 Parameters
@@ -291,10 +291,6 b' def configure_inline_support(shell, backend, user_ns=None):'
291 shell : InteractiveShell instance
291 shell : InteractiveShell instance
292
292
293 backend : matplotlib backend
293 backend : matplotlib backend
294
295 user_ns : dict
296 A namespace where all configured variables will be placed. If not given,
297 the `user_ns` attribute of the shell object is used.
298 """
294 """
299 # If using our svg payload backend, register the post-execution
295 # If using our svg payload backend, register the post-execution
300 # function that will pick up the results for display. This can only be
296 # function that will pick up the results for display. This can only be
@@ -309,8 +305,6 b' def configure_inline_support(shell, backend, user_ns=None):'
309 return
305 return
310 from matplotlib import pyplot
306 from matplotlib import pyplot
311
307
312 user_ns = shell.user_ns if user_ns is None else user_ns
313
314 cfg = InlineBackend.instance(parent=shell)
308 cfg = InlineBackend.instance(parent=shell)
315 cfg.shell = shell
309 cfg.shell = shell
316 if cfg not in shell.configurables:
310 if cfg not in shell.configurables:
@@ -335,57 +329,5 b' def configure_inline_support(shell, backend, user_ns=None):'
335 del shell._saved_rcParams
329 del shell._saved_rcParams
336
330
337 # Setup the default figure format
331 # Setup the default figure format
338 fmt = cfg.figure_format
332 select_figure_format(shell, cfg.figure_format)
339 select_figure_format(shell, fmt)
340
341
342 def pylab_activate(user_ns, gui=None, import_all=True, shell=None, welcome_message=False):
343 """Activate pylab mode in the user's namespace.
344
333
345 Loads and initializes numpy, matplotlib and friends for interactive use.
346
347 Parameters
348 ----------
349 user_ns : dict
350 Namespace where the imports will occur.
351
352 gui : optional, string
353 A valid gui name following the conventions of the %gui magic.
354
355 import_all : optional, boolean
356 If true, an 'import *' is done from numpy and pylab.
357
358 welcome_message : optional, boolean
359 If true, print a welcome message about pylab, which includes the backend
360 being used.
361
362 Returns
363 -------
364 The actual gui used (if not given as input, it was obtained from matplotlib
365 itself, and will be needed next to configure IPython's gui integration.
366 """
367 pylab_gui_select = shell.pylab_gui_select if shell is not None else None
368 # Try to find the appropriate gui and backend for the settings
369 gui, backend = find_gui_and_backend(gui, pylab_gui_select)
370 if shell is not None and gui != 'inline':
371 # If we have our first gui selection, store it
372 if pylab_gui_select is None:
373 shell.pylab_gui_select = gui
374 # Otherwise if they are different
375 elif gui != pylab_gui_select:
376 print ('Warning: Cannot change to a different GUI toolkit: %s.'
377 ' Using %s instead.' % (gui, pylab_gui_select))
378 gui, backend = find_gui_and_backend(pylab_gui_select)
379 activate_matplotlib(backend)
380 if import_all:
381 import_pylab(user_ns)
382 if shell is not None:
383 configure_inline_support(shell, backend, user_ns)
384 if welcome_message:
385 print """
386 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
387 For more information, type 'help(pylab)'.""" % backend
388 # flush stdout, just to be safe
389 sys.stdout.flush()
390
391 return gui
@@ -201,7 +201,9 b' class InteractiveShellApp(Configurable):'
201 gui, backend = pylabtools.find_gui_and_backend(self.pylab)
201 gui, backend = pylabtools.find_gui_and_backend(self.pylab)
202 self.log.info("Enabling GUI event loop integration, "
202 self.log.info("Enabling GUI event loop integration, "
203 "toolkit=%s, pylab=%s" % (gui, self.pylab))
203 "toolkit=%s, pylab=%s" % (gui, self.pylab))
204 shell.enable_pylab(gui, import_all=self.pylab_import_all, welcome_message=True)
204 if self.pylab == "auto":
205 print ("using matplotlib backend: %s" % backend)
206 shell.enable_pylab(self.pylab, import_all=self.pylab_import_all)
205 else:
207 else:
206 self.log.info("Enabling GUI event loop integration, "
208 self.log.info("Enabling GUI event loop integration, "
207 "toolkit=%s" % self.gui)
209 "toolkit=%s" % self.gui)
General Comments 0
You need to be logged in to leave comments. Login now