在IPython Notebook中自动运行%matplotlib inline

96

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

%matplotlib inline

有没有办法更改我的配置文件,使得当我启动IPython时,它自动进入这种模式?


1
'ipython -pylab' 能用吗? - Chris Arena
如果是这样,你可以很容易地将ipython别名设置为只执行那个操作。 - Chris Arena
5
"ipython --matplotlib" 更好。 - tacaswell
请忽略此悬赏。所选答案确实适用于5.5.0版本。强制性的24小时期限结束后,我将关闭此悬赏。对此感到抱歉! - Ricardo Magalhães Cruz
我敢打赌,你花了比把它直接粘贴到笔记本开头更多的时间来输入这个问题并尝试实现解决方案:D - Intelligent-Infrastructure
7个回答

87

配置方式

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

  • ipython_config.py
  • ipython_kernel_config.py

将inline选项添加到ipython_kernel_config.py中的matplotlib:

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

matplotlib与pylab之比较

%pylab的使用被不建议。它会将许多您不需要的东西注入到您的命名空间中。

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

import matplotlib.pyplot as plt
import numpy as np

通过明确地输入您的导入模块,所需的工作量微不足道,而您现在具有可重现的代码这一事实完全可以弥补此点成本。


2
谢谢。我实际上在matplotlib文档中看到了这个配置选项,但不确定它是否只是设置了matplotlib后端,该后端将在手动调用%matplotlib时生效,还是它既设置了默认后端,又自动设置以立即在iPython环境中使用。 - 8one6
3
关于matplotlibpylab,在@Kyle Kelley的编辑意见之外,我想补充一些内容。iPython使用Profile非常容易实现每次启动自动执行任意Python代码功能。通常会有一个Profile专门用来自动导入常用的包,例如import numpy as np; import pandas as pd; import matplotlib.pyplot as plt等等。请注意,pylab并不等同于pyplot,这个误解曾经困扰了我整整一个月。 - 8one6
3
这个方法(以及SillyBear的答案)在IPython 3中已经不再适用。https://github.com/ipython/docker-notebook/pull/7#issuecomment-54729770 建议使用"c.IPKernel.matplotlib"……但这也行不通。 - Pietro Battiston
3
这个回答对我有用。在IPython 3中,似乎有一个新的配置文件 ipython_kernel_config.py,其中包含这个选项。创建一个新的配置文件(ipython profile create test)以获取默认设置。 - DGrady
3
这个选项似乎已被重命名为c.InteractiveShellApp.matplotlib =“inline” - tiago
显示剩余4条评论

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)

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

$ 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的每个环境都有全局影响。如果您想通过单一更改在所有环境中具有共同行为,那么您也可以将其视为优点。
因此,请根据您的要求选择您想要使用的方法。

6
我认为您想要的是从命令行运行以下内容:
ipython notebook --matplotlib=inline

如果您不喜欢每次在cmd命令行中输入它,那么您可以创建一个别名来代替您进行操作。


1
请将您的帖子更改为 --matplotlib inline 并删除 --pylab 部分。请参阅此 ipython 开发人员的帖子,了解原因:http://carreau.github.io/posts/10-No-PyLab-Thanks.ipynb.html - Jakob
1
关于 matplotlib=inline 的一点说明:它会减慢您启动的每个内核,无论您是否想使用 matplotlib。 - Kyle Kelley
7
这种方法已经不再可行了(至少在IPython 4版本之后)。命令行选项“--matplotlib”或“--pylab”将被忽略。 - tiago
1
Jupyter 命令行帮助中提到这些选项已被禁用,建议使用 %pylab%matplotlib 代替。 - Cas

4

~/.ipython/profile_default/startup/ 目录下创建任何一个 .py 文件,包含以下内容:

get_ipython().magic('matplotlib inline')

1
从iPython 8.3版本开始,正确的格式已经变为get_ipython().run_line_magic('matplotlib', 'inline') - Alper
谢谢 @Alper - 你有文档的链接吗? - flow2k
1
没问题。请查看https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html#IPython.core.interactiveshell.InteractiveShell.run_line_magic和https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html#IPython.core.interactiveshell.InteractiveShell.magic。 - Alper

3

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

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

~/.ipython/profile_default/ipython_kernel_config.py

请添加下面这行代码

c.IPKernelApp.matplotlib = 'inline'

在此之后直接添加

c = get_config()

3
在你的 ipython_config.py 文件中,查找以下行。
# c.InteractiveShellApp.matplotlib = None

并且

# c.InteractiveShellApp.pylab = None

取消注释下列代码。然后将 None 更改为您正在使用的后端(我使用 'qt4'),保存文件。重新启动 IPython,matplotlib 和 pylab 将被加载-您可以使用 dir() 命令验证哪些模块在全局命名空间中。


2
进一步参考@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

to

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

这样做可以在IPython QT控制台和笔记本会话中都起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接