pylab.X vs pylab.plt.X - python
I noticed that there some names are duplicated in pylab. Say I import pylab. Here are some examples:
E.g. 1 :
pylab.ion()
pylab.plt.ion()
E.g. 2
pylab.figure(1)
pylab.plot.figure(1)
Is there any difference between them? Why have the two of them?
You can always check:
>>> pylab.ion is pylab.plt.ion
True
So, they are the same function.
Some names are duplicated, probably historical reasons and to enable backward compatibility...
There is an unwritten convention to import matplotlib as:
import matplotlib.pyplot as plt
if you want just the plotting functionality.
Importing pylab creates a Matlab like environment with a lot of functionalities from NumPy. (so this is also a reason for name duplication)
If you read the source (the entirety of pylab.py excluding the docstring is below)
from __future__ import print_function
import sys, warnings
from matplotlib.cbook import flatten, is_string_like, exception_to_str, \
silent_list, iterable, dedent
import matplotlib as mpl
# make mpl.finance module available for backwards compatability, in case folks
# using pylab interface depended on not having to import it
import matplotlib.finance
from matplotlib.dates import date2num, num2date,\
datestr2num, strpdate2num, drange,\
epoch2num, num2epoch, mx2num,\
DateFormatter, IndexDateFormatter, DateLocator,\
RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\
DayLocator, HourLocator, MinuteLocator, SecondLocator,\
rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY,\
WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, relativedelta
import matplotlib.dates # Do we need this at all?
# bring all the symbols in so folks can import them from
# pylab in one fell swoop
## We are still importing too many things from mlab; more cleanup is needed.
from matplotlib.mlab import griddata, stineman_interp, slopes, \
inside_poly, poly_below, poly_between, \
is_closed_polygon, path_length, distances_along_curve, vector_lengths
from matplotlib.mlab import window_hanning, window_none, detrend, demean, \
detrend_mean, detrend_none, detrend_linear, entropy, normpdf, levypdf, \
find, longest_contiguous_ones, longest_ones, prepca, \
prctile, prctile_rank, \
center_matrix, rk4, bivariate_normal, get_xyz_where, \
get_sparse_matrix, dist, \
dist_point_to_segment, segments_intersect, fftsurr, movavg, \
exp_safe, \
amap, rms_flat, l1norm, l2norm, norm_flat, frange, identity, \
base_repr, binary_repr, log2, ispower2, \
rec_append_fields, rec_drop_fields, rec_join, csv2rec, rec2csv, isvector
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
from numpy import *
from numpy.fft import *
from numpy.random import *
from numpy.linalg import *
from matplotlib.pyplot import *
# provide the recommended module abbrevs in the pylab namespace
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
# don't let numpy's datetime hide stdlib
import datetime
if sys.version_info > (2, 6, 0):
bytes = __builtins__['bytes']
you see that both every thing from pyplot is imported (from matplotlb.pyplot import * and pyplot) and pyplot is imported (import pyplot as plt). You are not seeing two functions, you are seeing the same function/module imported multiple times.
As to why, why not? pylab is designed for interactive use. It is convenient to have all the function directly in your name space and it is quite handy to have plt in the name space as well for prototyping code.
Related
Pandas/Numpy Errors in Eclipse
I am working in python and eclipse for the first time and i am having troubles. This is the code I have now from pandas import pandas as pd from numpy import numpy as np update = pd.read_csv("PPList.txt") My error says that the read_csv is an undefined from import My previous searches indicates that i need to change from numpy import numpy as np to just import numpy * When I do that, the * has an error saying that it's expecting a comma or colon.
The imports should be import pandas as pd import numpy as np Or from pandas import * from numpy import *
How to import single function from packages with the same name
What should I do about this? It seems python is calling the first function. from numpy.random import multivariate_normal from scipy.stats import multivariate_normal
The usual convention is: import numpy as np np.random.multivariate_normal Then there won't be such collisions.
abort trap when using matplotlib.pyplot after import caffe in python
My problem is that it occurs an abort trap when using matplotlib.pyplot after import caffe however there is no problem if using matplotlib.pyplot before import caffe.I run this with python2.7 on macos10.12.4. Here is my wrong code: #!/usr/bin/python #encoding=utf-8 import numpy as np import matplotlib.pyplot as plt import caffe plt.plot([0,1],[0,2]) plt.show() The output is: src/tcmalloc.cc:284] Attempt to free invalid pointer 0x7feb5f158af0 Abort trap: 6 There will be no problem like this: #!/usr/bin/python #encoding=utf-8 import numpy as np import matplotlib.pyplot as plt plt.plot([0,1],[0,2]) plt.show() import caffe But i need to use plt after 'import caffe'. How to fix it?
Error when importing modules
I'm getting the following error when importing modules in python. I'm using jupyter notebook (python 2). I've searched through the internet but still can't quite figure out why. Any help would be so much appreciated. Here's the code: import numpy as np from pandas import Series,DataFrame import pandas as pd --------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-e4e9959b303a> in <module>() ----> 1 import numpy as np 2 from pandas import Series,DataFrame 3 import pandas as pd /Users/...filepath.../Python/data_analysis/numpy.pyc in <module>() 17 18 import numpy as np ---> 19 from numpy.random import randn 20 21 ImportError: No module named random I've tried adding import random to the above code (before the other modules) and it still gives the same error. Could this be due to the version of gfortran on my system? I have version 4.9.2
Since I dont have complete code, just tried using import statements. If we use np as per #John import numpy as np from np.random import randn I am getting from np.random import randn ImportError: No module named np.random I am not getting any error if I import randn from numpy.random import numpy as np from numpy.random import randn print "randn1= ", randn() from numpy.random import rand print "rand1= ", rand() Its working for me with output as below, randn1= 0.147667079884 rand1= 0.243935746205 You can also try to use np.random.randn() and np.random.rand() directly. import numpy as np print "randn2= ", np.random.randn() print "rand2= ", np.random.rand() I get : randn2= -0.22571513741 rand2= 0.486507681046
How can I use numpy functions within NumbaPro functions?
I am new to CUDA, I am trying to use NumbaPro's cuda extension to compute some exponentials, however I cannot seem to use numpy within the cuda complied functions? I know i am doing something silly, but I cannot figure it out. import numpy as np from pylab import imshow, show, plot from timeit import default_timer as timer from numbapro import cuda from numba import * import math def Deng_test(xx,Expre): ExTest = (np.abs(np.sum(Expre)))**2 return ExTest Deng_test_gpu = cuda.jit(argtypes=(double,complex128), restype=float64, device=True, inline=True)(Deng_test)