Automatically run %matplotlib inline in IPython Notebook

后端 未结 7 1431
逝去的感伤
逝去的感伤 2020-11-28 20:06

Every time I launch IPython Notebook, the first command I run is

%matplotlib inline

Is there some way to change my config file so that when

相关标签:
7条回答
  • 2020-11-28 20:45

    Create any .py file in ~/.ipython/profile_default/startup/ containing

    get_ipython().magic('matplotlib inline')
    
    0 讨论(0)
  • 2020-11-28 20:46

    I think what you want might be to run the following from the command line:

    ipython notebook --matplotlib=inline
    

    If you don't like typing it at the cmd line every time then you could create an alias to do it for you.

    0 讨论(0)
  • 2020-11-28 20:48

    The configuration way

    IPython has profiles for configuration, located at ~/.ipython/profile_*. The default profile is called profile_default. Within this folder there are two primary configuration files:

    • ipython_config.py
    • ipython_kernel_config.py

    Add the inline option for matplotlib to ipython_kernel_config.py:

    c = get_config()
    # ... Any other configurables you want to set
    c.InteractiveShellApp.matplotlib = "inline"
    

    matplotlib vs. pylab

    Usage of %pylab to get inline plotting is discouraged.

    It introduces all sorts of gunk into your namespace that you just don't need.

    %matplotlib on the other hand enables inline plotting without injecting your namespace. You'll need to do explicit calls to get matplotlib and numpy imported.

    import matplotlib.pyplot as plt
    import numpy as np
    

    The small price of typing out your imports explicitly should be completely overcome by the fact that you now have reproducible code.

    0 讨论(0)
  • 2020-11-28 20:58

    In (the current) IPython 3.2.0 (Python 2 or 3)

    Open the configuration file within the hidden folder .ipython

    ~/.ipython/profile_default/ipython_kernel_config.py
    

    add the following line

    c.IPKernelApp.matplotlib = 'inline'
    

    add it straight after

    c = get_config()
    
    0 讨论(0)
  • 2020-11-28 21:04

    The setting was disabled in Jupyter 5.X and higher by adding below code

    pylab = Unicode('disabled', config=True,
        help=_("""
        DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
        """)
    )
    
    @observe('pylab')
    def _update_pylab(self, change):
        """when --pylab is specified, display a warning and exit"""
        if change['new'] != 'warn':
            backend = ' %s' % change['new']
        else:
            backend = ''
        self.log.error(_("Support for specifying --pylab on the command line has been removed."))
        self.log.error(
            _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
        )
        self.exit(1)
    

    And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

    $ jupyter kernelspec list
    Available kernels:
      python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3
    

    This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

    {
     "argv": [
      "python",
      "-m",
      "ipykernel_launcher",
      "-f",
      "{connection_file}",
     ],
     "display_name": "Python 3",
     "language": "python"
    }
    

    So you can see what command is executed to launch the kernel. So if you run the below command

    $ python -m ipykernel_launcher --help
    IPython: an enhanced interactive Python shell.
    
    Subcommands
    -----------
    
    Subcommands are launched as `ipython-kernel cmd [args]`. For information on
    using subcommand 'cmd', do: `ipython-kernel cmd -h`.
    
    install
        Install the IPython kernel
    
    Options
    -------
    
    Arguments that take values are actually convenience aliases to full
    Configurables, whose aliases are listed on the help line. For more information
    on full configurables, see '--help-all'.
    
    ....
    --pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
        Default: None
        Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
        Pre-load matplotlib and numpy for interactive use, selecting a particular
        matplotlib backend and loop integration.
    --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
        Default: None
        Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
        Configure matplotlib for interactive use with the default matplotlib
        backend.
    ...    
    To see all available configurables, use `--help-all`
    

    So now if we update our kernel.json file to

    {
     "argv": [
      "python",
      "-m",
      "ipykernel_launcher",
      "-f",
      "{connection_file}",
      "--pylab",
      "inline"
     ],
     "display_name": "Python 3",
     "language": "python"
    }
    

    And if I run jupyter notebook the graphs are automatically inline

    Note the below approach also still works, where you create a file on below path

    ~/.ipython/profile_default/ipython_kernel_config.py

    c = get_config()
    c.IPKernelApp.matplotlib = 'inline'
    

    But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

    So choose which approach you would like to use based on your requirement

    0 讨论(0)
  • 2020-11-28 21:09

    In your ipython_config.py file, search for the following lines

    # c.InteractiveShellApp.matplotlib = None
    

    and

    # c.InteractiveShellApp.pylab = None
    

    and uncomment them. Then, change None to the backend that you're using (I use 'qt4') and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir() command to verify which modules are in the global namespace.

    0 讨论(0)
提交回复
热议问题