gpt4 book ai didi

python - matplotlib.pyplot 与 matplotlib.pylab

转载 作者:太空狗 更新时间:2023-10-29 16:57:00 25 4
gpt4 key购买 nike

我通常使用以下包来创建我的绘图: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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com