在IPython Notebook中自动运行%matplotlib内联

8on*_*ne6 86 python matplotlib ipython-notebook

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

%matplotlib inline
Run Code Online (Sandbox Code Playgroud)

有没有办法改变我的配置文件,以便在我启动IPython时,它会自动进入这种模式?

Kyl*_*ley 77

配置方式

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"
Run Code Online (Sandbox Code Playgroud)

matplotlib与pylab

不鼓励使用%pylab内联绘图.

它将各种gunk引入您不需要的命名空间.

%matplotlib另一方面,无需注入命名空间即可启用内联绘图.你需要进行显式调用才能获得matplotlib和numpy导入.

import matplotlib.pyplot as plt
import numpy as np
Run Code Online (Sandbox Code Playgroud)

显而易见地输入您的输入的小代价应该通过您现在具有可重现的代码完全克服.

  • 要添加到@Kyle Kelley关于`matplotlib` vs`pylab`的编辑,iPython使每次使用Profiles启动时都可以很容易地自动执行任意python代码.我相信有一个配置文件很常见,你自动执行常见的导入,如`import numpy as np; 将pandas导入为pd; 将matplotlib.pyplot导入为plt`等.注意:`pylab`不是**与'pyplot`相同的东西.我必须花一个月才能意识到这一点. (3认同)
  • 这(以及SillyBear的答案)停止使用IPython 3. https://github.com/ipython/docker-notebook/pull/7#issuecomment-54729770建议使用"c.IPKernel.matplotlib"......不工作. (3认同)
  • [这个答案](http://stackoverflow.com/a/28970252/514210)为我工作.在IPython 3中,显然有一个包含此选项的新配置文件`ipython_kernel_config.py`.创建一个新的配置文件(`ipython profile create test`)以获取默认值. (3认同)
  • 此选项似乎已重命名为`c.InteractiveShellApp.matplotlib ="inline"` (3认同)
  • 谢谢.我实际上已经在matplotlib文档中看到了这个配置选项,但是不确定它是否只是设置了matplotlib后端,一旦你手动调用`%matplotlib`*就会生效*或者它是否都设置了默认的后端并且*自动设置它*立即在iPython环境中使用. (2认同)

小智 6

我想你想要的是从命令行运行以下命令:

ipython notebook --matplotlib=inline
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢每次都在cmd行输入它,那么您可以创建一个别名来为您完成.

  • 这不再有效(至少从IPython 4开始).命令行选项`--matplotlib`或`--pylab`将被忽略. (7认同)

Tar*_*ani 6

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)
Run Code Online (Sandbox Code Playgroud)

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

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3
Run Code Online (Sandbox Code Playgroud)

这给了我内核文件夹的路径。现在,如果我打开/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"
}
Run Code Online (Sandbox Code Playgroud)

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

$ 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`
Run Code Online (Sandbox Code Playgroud)

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

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}
Run Code Online (Sandbox Code Playgroud)

如果我运行jupyter notebook图表是自动的inline

自动内联

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

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'
Run Code Online (Sandbox Code Playgroud)

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

因此,请根据您的要求选择您想使用的方法