推荐哪种绘制方式:matplotlib或pylab? [英] Which is the recommended way to plot: matplotlib or pylab?
问题描述
我发现我可以使用以下任一方法在 Python 中进行绘制:
import matplotlib
matplotlib.pyplot.plot(...)
或者:
import pylab
pylab.plot(...)
这两个都使用相同的 matplotlib 绘图代码.
那么,Matplotlib开发人员/文档当前推荐使用哪种方法作为更好的绘图方法?为什么?
官方文档:如何将pyplot函数附加到图形实例? >
pylab
是将大量有用的功能(pyplot
状态机功能,大部分numpy
的大部分)批量导入单个名称空间的一种简便方法.存在的主要原因(据我了解)是与ipython
一起使用以制作一个非常好用的交互式shell,它或多或少地复制了MATLAB(以使转换更容易,因为它很适合玩耍).参见 pylab.py
和 解决方案
Official docs: Matplotlib, pyplot and pylab: how are they related?
Both of those imports boil down do doing exactly the same thing and will run the exact same code, it is just different ways of importing the modules.
Also note that matplotlib
has two interface layers, a state-machine layer managed by pyplot
and the OO interface pyplot
is built on top of, see How can I attach a pyplot function to a figure instance?
pylab
is a clean way to bulk import a whole slew of helpful functions (the pyplot
state machine function, most of numpy
) into a single name space. The main reason this exists (to my understanding) is to work with ipython
to make a very nice interactive shell which more-or-less replicates MATLAB (to make the transition easier and because it is good for playing around). See pylab.py
and matplotlib/pylab.py
At some level, this is purely a matter of taste and depends a bit on what you are doing.
If you are not embedding in a gui (either using a non-interactive backend for bulk scripts or using one of the provided interactive backends) the typical thing to do is
import matplotlib.pyplot as plt
import numpy as np
plt.plot(....)
which doesn't pollute the name space. I prefer this so I can keep track of where stuff came from.
If you use
ipython --pylab
this is equivalent to running
from pylab import *
It is now recommended that for new versions of ipython
you use
ipython --matplotlib
which will set up all the proper background details to make the interactive backends to work nicely, but will not bulk import anything. You will need to explicitly import the modules want.
import numpy as np
import matplotlib.pyplot as plt
is a good start.
If you are embedding matplotlib
in a gui you don't want to import pyplot as that will start extra gui main loops, and exactly what you should import depends on exactly what you are doing.
这篇关于推荐哪种绘制方式:matplotlib或pylab?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!