matplotlib.pyplot vs matplotlib.pylab



我通常使用以下包来创建我的绘图:matplotlib.pylab。然而,还有一个名为matplotlib.pyplot的包。

在使用它们时,我无法发现两者之间的任何区别。所以我的问题是:

matplotlib.pylabmatplotlib.pyplot之间的区别是什么。在哪种情况下,你会建议一种而不是另一种?

根据常见问题解答:

Pyplot为底层绘图提供了状态机接口matplotlib中的库。这意味着图形和轴是隐含的并自动创建以实现所需的绘图。。。。

Pylab将pyplot功能(用于打印(与numpy相结合函数(用于数学和使用数组(单个名称空间,使该名称空间(或环境(更加丰富类似MATLAB。例如,可以只调用sin和cos函数就像在MATLAB中一样,并且具有pyplot。

pyplot界面通常是非交互式的首选界面绘图(即脚本(pylab接口方便交互式计算和打印,因为它最大限度地减少了打字。(我强调(

注意

from pylab import *

还执行

from numpy import *

这会覆盖许多内置Python函数,例如:

In [5]: import __builtin__
In [6]: import numpy as np
In [5]: {name for name in set(dir(np)).intersection(dir(__builtin__)) if not name.startswith('__') and getattr(__builtin__, name) != getattr(np, name)}
Out[5]: {'abs', 'all', 'any', 'max', 'min', 'round', 'sum'}

因此,我不喜欢from pylab import *(或者任何模块的from module import *(,因为它会让众所周知的Python名称以意想不到的方式表现(如果你不总是记住from numpy import *污染了全局命名空间的话(

例如,

In [32]: np.all([np.arange(3), np.arange(3)])
Out[32]: False

In [33]: all([np.arange(3), np.arange(3)])
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最新更新