在IPython笔记本中自动运行%matplotlib inline

2024-04-24 03:41:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

%matplotlib inline

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


Tags: 方法命令matplotlib配置文件ipython模式inline笔记本
3条回答

配置方式

IPython的配置配置文件位于~/.ipython/profile_*。默认配置文件名为profile_default。此文件夹中有两个主配置文件:

  • ipython_config.py
  • ipython_kernel_config.py

将matplotlib的inline选项添加到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

显式地输入导入的小代价应该完全被这样一个事实所克服:您现在有了可复制的代码。

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

ipython notebook --matplotlib=inline

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

通过添加以下代码,在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

Auto Inline

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

~/.ipython/profile_default/ipython_kernel_config.py

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

但这种方法的缺点是,这会对使用python的每个环境产生全局影响。如果您希望在单个更改的环境中有一个共同的行为,也可以将此视为一个优势。

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

相关问题 更多 >