python - matplotlib.pyplot 与 matplotlib.pylab

标签 python matplotlib

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

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

matplotlib.pylabmatplotlib.pyplot 有什么区别。在哪些情况下,您会建议一个而不是另一个?

最佳答案

根据 the FAQ :

Pyplot provides the state-machine interface to the underlying plotting library in matplotlib. This means that figures and axes are implicitly and automatically created to achieve the desired plot....

Pylab combines the pyplot functionality (for plotting) with the numpy functionality (for mathematics and for working with arrays) in a single namespace, making that namespace (or environment) even more MATLAB-like. For example, one can call the sin and cos functions just like you could in MATLAB, as well as having all the features of pyplot.

The pyplot interface is generally preferred for non-interactive plotting (i.e., scripting). The pylab interface is convenient for interactive calculations and plotting, as it minimizes typing. (my emphasis.)

注意

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()

关于python - matplotlib.pyplot 与 matplotlib.pylab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451028/

相关文章:

python - 为什么 asyncio.Queue 无法按预期工作?

python - 如何在 python 中使用 opencv 按下按键时准确地从相机流中捕获帧?

python - 使用 scipy.signal 在 Python 中进行卷积和反卷积

python - 如何使用 matplotlib 创建相等数量的主要和次要 y 轴刻度?

Python - 一个图中的两个数字

python - 如何在条形图上添加值标签

python - tweepy stream.filter() 方法不能正常工作

python - WebSocketHandler 和 TornadoWebSocketClient 何时完全删除?

python - 如何更改 matplotlib 在绘制时间戳对象时使用的步长?

python - Matplotlib Pyplot 条形图中的 float 条形