什么是%pylab?

2024-05-22 00:08:48 发布

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

我一直看到人们在各种代码片段中使用%pylab,特别是在iPython中。然而,我看不到在学习Python的任何地方(以及我所拥有的其他几本Python书籍)都提到了%pylab,也不知道它的真正含义。

我相信答案很简单,但有人能启发我吗?


Tags: 答案代码地方ipython书籍含义pylab
3条回答

%pylab是一个“神奇函数”,您可以在IPython或Interactive Python中调用它。通过调用它,IPython解释器将导入matplotlibNumPy模块,这样您就可以方便地访问它们的函数。举个例子

rich@rich-ubuntu:~/working/fb_recruit/working$ ipython
Python 2.7.6 |Anaconda 1.8.0 (64-bit)| (default, Nov 11 2013, 10:47:18) 
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: arange(4)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-2e43d7eb1b3e> in <module>()
----> 1 arange(4)

NameError: name 'arange' is not defined

In [2]: %pylab
Using matplotlib backend: Qt4Agg
Populating the interactive namespace from numpy and matplotlib

In [3]: arange(4)
Out[3]: array([0, 1, 2, 3])

In [4]: 

%pylab是键入以下所有命令的快捷方式,这些命令实质上是将numpy和matplotlib添加到会话中。这是作为转换工具添加到IPython中的,目前的建议是不应该使用它。核心原因是下面的命令集在全局命名空间中导入过多,而且不允许您将matplotlib的模式从UI更改为QT或其他方式。你可以在http://nbviewer.ipython.org/github/Carreau/posts/blob/master/10-No-PyLab-Thanks.ipynb?create=1找到这背后的历史和推理。

这就是%pylab所做的:

import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot

from IPython.core.pylabtools import figsize, getfigs

from pylab import *
from numpy import *

这是我在笔记本开始时使用的功能:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

%pylab是ipython中的一个神奇功能。

ipython中的Magic函数总是以百分号(%)开头,后面没有空格,后面是一个小文本字符串;实际上,ipython Magic函数定义了对交互工作特别有用的快捷方式,例如,为了让您了解Magic函数在python中的工作原理,我的一些最爱:

  • 查看cwd目录内容:

    %ls   
    
  • 要在ipython中使用空命名空间运行脚本,请键入space,然后键入脚本名:

    %run     
    
  • 执行代码段(特别是多行代码段,这通常会导致抛出一个“IndentationError”:

    %paste
    

当在IPython提示符下输入%pylab魔术函数时,它会触发 在Matplotlib中导入各种模块。

哪些模块?好吧,那些包含在pylab界面下。

awesome Matplotlib绘图库有两个不同的界面:pythonic界面和原始的类似于MATLAB的界面,用于在交互提示下绘图。

前者通常是这样进口的:

from matplotlib import pyplot as PLT

实际上,pyplot有自己的神奇python魔法函数

%pyplot

为什么有两个不同的接口?Matplotlib的原始接口是pylab;仅 后来添加了pythonic接口。脚本和应用程序开发没有 项目开始时Matplotlib的主要用例,在 Python壳是。

John Hunter(Matplotlib的创建者)希望在python中包含交互式绘图,因此他向Fernando Perez(FP)IPython项目提交了一个补丁。当时,FP是一名博士生,他告诉JH他有一段时间不能复习这条路了。因此,JH创建了Matplotlib。重要的是Matplotlib最初是一个基于shell的绘图方案。

pylab接口确实更适合交互式工作:

from pylab import *

x, y = arange(10), cos(x/2)
plot(x, y)
show()

使用pyplot接口:

from matplotlib import pyplot as PLT
import numpy as NP

x, y = NP.arange(10), NP.cos(x/2)
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y)
PLT.show()

相关问题 更多 >