What is the difference between pylab and pyplot?
This wording is no longer in the documentation.
Use of the pylab
import is now discouraged and the OO interface is recommended for most non-interactive usage.
From the documentation, the emphasis is mine:
Matplotlib is the whole package; pylab is a module in matplotlib that gets installed alongside matplotlib; and matplotlib.pyplot is a module in matplotlib.
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. For example, calling plot from pyplot will automatically create the necessary figure and axes to achieve the desired plot. Setting a title will then automatically set that title to the current axes object:
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. Note that this is what you get if you use the ipython shell with the -pylab option, which imports everything from pylab and makes plotting fully interactive.
matplotlib.pyplot vs matplotlib.pylab
Per 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.)
Note that
from pylab import *
also performs
from numpy import *
This overwrites many builtin Python functions such as:
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'}
Therefore, I don't like from pylab import *
(or really from module import *
for any module) because it makes well-known beloved Python names behave in unexpected ways (if you do not always keep in mind that from numpy import *
has polluted the global namespace.)
For example,
In [32]: np.all([np.arange(3), np.arange(3)])
Out[32]: False
while
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()
Which is the recommended way to plot: matplotlib or pylab?
From the official documentation, as shown below, the recommendation is to use matplotlib.pyplot
. This is not an opinion.
The documentation at Matplotlib, pyplot and pylab: how are they related?, which also describes the difference between pyplot and pylab, states: "Although many examples use pylab, it is no longer recommended.".
2021-05-06 Edit:
- From The pylab API (disapproved)
Since heavily importing into the global namespace may result in unexpected behavior, the use of pylab is strongly discouraged. Use matplotlib.pyplot instead.
Confusion between numpy, scipy, matplotlib and pylab
No,
pylab
is part ofmatplotlib
(inmatplotlib.pylab
) and tries to give you a MatLab like environment.matplotlib
has a number of dependencies, among themnumpy
which it imports under the common aliasnp
.scipy
is not a dependency ofmatplotlib
.If you run
ipython --pylab
an automatic import will put all symbols frommatplotlib.pylab
into global scope. Like you wrotenumpy
gets imported under thenp
alias. Symbols frommatplotlib
are available under thempl
alias.
What is the difference between importing matplotlib and matplotlib.pyplot?
I don't know of any way to import all the functions from every submodule. Importing all the functions from a submodule is possible the way you suggested with e.g. from matplotlib.pyplot import *
.
Be noted of a potential problem with importing every function; you may override imported functions by defining your own functions with the same name. E.g:
from matplotlib.pyplot import *
def plot():
print "Hello!"
plot()
would output
Hello!
What is the difference between `matplotlib.rc` and `matplotlib.rcParams`? And which one to use?
matplotlib.rc
is a function that updates matplotlib.rcParams
.
matplotlib.rcParams
is a dict-subclass that provides a validate key-value map for Matplotlib configuration.
The docs for mpl.rc
are at https://matplotlib.org/stable/api/matplotlib_configuration_api.html?highlight=rc#matplotlib.rc and the code is here.
The class definition of RcParams
is here and it the instance is created here.
If we look at the guts of matplotlib.rc
we see:
for g in group:
for k, v in kwargs.items():
name = aliases.get(k) or k
key = '%s.%s' % (g, name)
try:
rcParams[key] = v
except KeyError as err:
raise KeyError(('Unrecognized key "%s" for group "%s" and '
'name "%s"') % (key, g, name)) from err
where we see that matplotlib.rc
does indeed update matplotlib.rcParams
(after doing some string formatting).
You should use which ever one is more convenient for you. If you know exactly what key you want to update, then interacting with the dict-like is better, if you want to set a whole bunch of values in a group then mpl.rc
is likely better!
What is the difference between (matplotlib) and (SymPy Plotting Module)?
①Why is it that the above source code can be used to create a plot, but the following source code cannot?
The linked example uses matplotlib which works with numeric inputs. Matplotlib doesn't know about sympy's world.
Sympy's plot module converts sympy expressions to numeric approximations and plots them using matplotlib. Sympy's plot module abstracts away a lot of intricacies to make this work, and hides these from the casual user.
②Can you point me to a web site that has a table comparing (matplotlib) and (SymPy Plotting Module)?
Matplotlib is very huge. Sympy's plotting module uses a subset of functionality, carefully and ingeniously adapted to the symbolic world. Differences don't fit into a table. Matplotlib's extensive documentation can be found at matplotlib.org, but most people only look into the subset they are using. Sympy's plotting documentation fits onto one large webpage. For both libraries you will need extra tutorials, StackOverlow, and maybe diving into the freely available source code if you need functionality that isn't readily available.
③(matplotlib) to (SymPy Plotting Module) converter and a (SymPy Plotting Module) to (matplotlib) converter would be helpful.
That would be a titanic work, with lots of undefined cases. Sympy (as well as matplotlib) is developed by very talented volunteers, with limited resources.
Note that, if you really want to, you can "move" sympy plots to the matplotlib world and extend the plot there.
Here is how your source code could look like in sympy.
First some remarks:
- sympy functions and expressions can't work with Python's
if
-tests, you need symbolic functions such asPieceWise
instead. float(x)
doesn't work for sympy's symbols- in general, sympy tries to avoid floats as they are approximate by definition while sympy almost always looks for exact symbolic solutions
from sympy import plot, Symbol, Piecewise, And
def define_fn(n):
def fn(x):
return Piecewise((x - n, (n <= x) & (x <= n + 1)),
(2 - x + n, (n + 1 <= x) & (x <= n + 2)),
(0, True))
return fn
f3 = define_fn(3)
f8 = define_fn(8)
x = Symbol('x', real=True)
plot(f3(x), f8(x), (x, -1, 11))
Although this works, it is not sympy's standard way. Usually, functions are written as expressions. Note how f3
is used as an expression that contains x
, instead of the less flexible f3(x)
of the previous example.
from sympy import plot, Symbol, Piecewise, And
x = Symbol('x', real=True)
n = Symbol('n', real=True)
fn = Piecewise((x - n, (n <= x) & (x <= n + 1)),
(2 - x + n, (n + 1 <= x) & (x <= n + 2)),
(0, True))
f3 = fn.subs(n, 3) # Piecewise((x - 3, (x >= 3) & (x <= 4)), (5 - x, (x >= 4) & (x <= 5)), (0, True))
f8 = fn.subs(n, 8) # Piecewise((x - 8, (x >= 8) & (x <= 9)), (10 - x, (x >= 9) & (x <= 10)), (0, True))
plot(f3, f8, (x, -1, 11))
Related Topics
Type Hint for a Function That Returns Only a Specific Set of Values
Add Sum of Values of Two Lists into New List
Python's JSON Module, Converts Int Dictionary Keys to Strings
Django Submit Two Different Forms with One Submit Button
Why Do "Not a Number" Values Equal True When Cast as Boolean in Python/Numpy
Easy Pretty Printing of Floats
Debugging (Displaying) SQL Command Sent to the Db by SQLalchemy
Multiprocessing in Python - Sharing Large Object (E.G. Pandas Dataframe) Between Multiple Processes
Retrieving a Foreign Key Value with Django-Rest-Framework Serializers
How to Loop Through All But the Last Item of a List
Override a Method at Instance Level
How to Set Env Variable in Jupyter Notebook
Python Multiprocessing: Handling Child Errors in Parent
Create a Day-Of-Week Column in a Pandas Dataframe Using Python
Django: Add Image in an Imagefield from Image Url