【问题标题】:Automatically run %matplotlib inline in IPython Notebook在 IPython Notebook 中自动运行 %matplotlib inline
【发布时间】:2014-02-06 05:48:56
【问题描述】:

每次我启动 IPython Notebook 时,我运行的第一个命令是

%matplotlib inline

有什么方法可以更改我的配置文件,以便在我启动 IPython 时,它会自动处于此模式?

【问题讨论】:

  • 'ipython -pylab' 工作吗?
  • 如果是这样,您可以使用 ipython 别名来轻松做到这一点。
  • ipython --matplotlib 更好
  • 请忽略赏金。所选答案适用于 5.5.0。我将在强制性 24 小时后关闭赏金。很抱歉!
  • 我打赌你花了更多时间输入这个问题并尝试实施解决方案,而不是简单地将其粘贴到笔记本的开头:D

标签: python matplotlib ipython-notebook


【解决方案1】:

~/.ipython/profile_default/startup/ 中创建任何包含.py 的文件

get_ipython().magic('matplotlib inline')

【讨论】:

    【解决方案2】:

    配置方式

    IPython 有配置文件,位于~/.ipython/profile_*。默认配置文件称为profile_default。在这个文件夹中有两个主要的配置文件:

    • ipython_config.py
    • ipython_kernel_config.py

    将matplotlib的内联选项添加到ipython_kernel_config.py

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

    matplotlib 与 pylab

    使用%pylab 进行内联绘图是discouraged

    它在你的命名空间中引入了你不需要的各种垃圾。

    %matplotlib 另一方面,可以在不注入命名空间的情况下进行内联绘图。您需要进行显式调用才能导入 matplotlib 和 numpy。

    import matplotlib.pyplot as plt
    import numpy as np
    

    您现在拥有可重现的代码这一事实应该完全克服了显式输入导入的小代价。

    【讨论】:

    • 谢谢。我实际上在 matplotlib 文档中看到了这个配置选项,但不确定它是否只是设置 matplotlib 后端会生效一旦你手动调用 %matplotlib 或者它是否都设置了默认后端并自动设置以便在 iPython 环境中立即使用。
    • 添加到@Kyle Kelley 对matplotlibpylab 的编辑中,iPython 使得每次使用 Profiles 启动时自动执行任意 python 代码变得非常容易。我相信拥有一个自动执行常见导入的配置文件是很常见的,例如import numpy as np; import pandas as pd; import matplotlib.pyplot as plt 等。注意:pylab pyplot 相同。我肯定花了一个月的时间才意识到这一点。
    • 这(以及 SillyBear 的回答)停止使用 IPython 3。github.com/ipython/docker-notebook/pull/7#issuecomment-54729770 建议使用“c.IPKernel.matplotlib”... 这也不起作用。
    • This answer 为我工作。在 IPython 3 中,显然有一个新的配置文件 ipython_kernel_config.py,其中包含此选项。创建一个新的配置文件 (ipython profile create test) 以获得默认值。
    • 这个选项好像改名为c.InteractiveShellApp.matplotlib = "inline"
    【解决方案3】:

    通过添加以下代码在Jupyter 5.X 及更高版本中禁用了该设置

    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)
    

    在以前的版本中,它主要是一个警告。但这不是一个大问题,因为 Jupyter 使用 kernels 的概念,您可以通过运行以下命令来找到您项目的内核

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

    这给了我内核文件夹的路径。现在,如果我打开 /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json 文件,我会看到类似下面的内容

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

    这样你就可以看到启动内核时执行了什么命令。所以如果你运行下面的命令

    $ 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`
    

    所以现在如果我们将kernel.json 文件更新为

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

    如果我运行jupyter notebook,图表会自动变为inline

    请注意,以下方法仍然有效,您可以在以下路径上创建文件

    ~/.ipython/profile_default/ipython_kernel_config.py

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

    但这种方法的缺点是,这对使用 python 的每个环境都有全局影响。如果您希望通过一次更改在不同环境中实现通用行为,您也可以将其视为一种优势。

    所以根据你的要求选择你想使用的方法

    【讨论】:

      【解决方案4】:

      除了@Kyle Kelley 和@DGrady,这里是可以在

      中找到的条目

      $HOME/.ipython/profile_default/ipython_kernel_config.py(或您创建的任何个人资料)

      改变

      # Configure matplotlib for interactive use with the default matplotlib backend.
      # c.IPKernelApp.matplotlib = none
      

      # Configure matplotlib for interactive use with the default matplotlib backend.
      c.IPKernelApp.matplotlib = 'inline'
      

      这将在 ipython qtconsole 和 notebook 会话中起作用。

      【讨论】:

        【解决方案5】:

        在(当前)IPython 3.2.0(Python 2 或 3)中

        打开隐藏文件夹.ipython中的配置文件

        ~/.ipython/profile_default/ipython_kernel_config.py
        

        添加下面一行

        c.IPKernelApp.matplotlib = 'inline'
        

        直接在后面加上

        c = get_config()
        

        【讨论】:

          【解决方案6】:

          我认为您想要的可能是从命令行运行以下命令:

          ipython notebook --matplotlib=inline
          

          如果您不喜欢每次都在 cmd 行中键入它,那么您可以创建一个别名来为您执行此操作。

          【讨论】:

          • 请将您的帖子更改为 --matplotlib inline 并删除 --pylab 内容。请参阅 ipython 开发人员的这篇文章为什么:carreau.github.io/posts/10-No-PyLab-Thanks.ipynb.html
          • 关于matplotlib=inline的一点说明:无论您是否要使用matplotlib,它都会减慢您启动的每个内核。
          • 这不再有效(至少从 IPython 4 开始)。命令行选项--matplotlib--pylab 被忽略。
          • Jupyter 命令行帮助的帮助说明这些选项已禁用,应改用 %pylab%matplotlib
          【解决方案7】:

          在您的 ipython_config.py 文件中,搜索以下行

          # c.InteractiveShellApp.matplotlib = None
          

          # c.InteractiveShellApp.pylab = None
          

          并取消注释它们。然后,将None 更改为您正在使用的后端(我使用'qt4')并保存文件。重启 IPython,matplotlib 和 pylab 应该会被加载——你可以使用dir() 命令来验证哪些模块在全局命名空间中。

          【讨论】:

            猜你喜欢
            • 2016-01-18
            • 1970-01-01
            • 1970-01-01
            • 2012-05-26
            • 1970-01-01
            • 2013-09-12
            • 2017-09-18
            • 1970-01-01
            相关资源
            最近更新 更多