Basic Imports

In [1]:
from numpy import *
import matplotlib.pyplot as plt

Basic Plot

In [2]:
x = arange(0.,10.,0.1) # generate a range of values as an array, using begin, end, step as input 
y = sin(x)
ll = plt.plot(x,y) # this is the simplest plotting idiom
plt.show()

Setting Plot Parameters and annotating

In [3]:
ll = plt.plot(x,y)
xl = plt.xlabel('horizontal axis')
yl = plt.ylabel('vertical axis')
ttl = plt.title('sine function')
ax = plt.axis([-2, 12, -1.5, 1.5])
grd = plt.grid(True)
txt = plt.text(0,1.3,'here is some text')
ann = plt.annotate('a point on curve',xy=(4.7,-1),xytext=(3,-1.3),arrowprops=dict(arrowstyle='->'))
plt.show()

Multiple Graphs On the Same Plot

In [4]:
x = arange(0.,10,0.1)
a = cos(x)
b = sin(x)
c = exp(x/10)
d = exp(-x/10)
la = plt.plot(x,a,'b-',label='cosine')
lb = plt.plot(x,b,'r--',label='sine')
lc = plt.plot(x,c,'gx',label='exp(+x)')
ld = plt.plot(x,d,'y-', linewidth = 5,label='exp(-x)')
ll = plt.legend(loc='upper left')
lx = plt.xlabel('xaxis')
ly = plt.ylabel('yaxis')
plt.show()

Plotting with multiple plots on a grid

Some neat tricks with legends, bg colors and arrows in labels

In [5]:
a = np.arange(0,3,.02)
b = np.arange(0,3,.02)
c = np.exp(a)
d = c[::-1]

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(a,c,'k--',a,d,'k:',a,c+d,'k')
leg = ax.legend(('Model length', 'Data length', 'Total message length'),
           'upper center', shadow=True)
ax.set_ylim([-1,20])
ax.grid(True)
ax.set_xlabel('Model complexity --->')
ax.set_ylabel('Message length --->')
ax.set_title('Minimum Message Length')

ax.set_yticklabels([])
ax.set_xticklabels([])

# set some legend properties.  All the code below is optional.  The
# defaults are usually sensible but if you need more control, this
# shows you how

# the matplotlib.patches.Rectangle instance surrounding the legend
frame  = leg.get_frame()
frame.set_facecolor('0.80')    # set the frame face color to light gray

# matplotlib.text.Text instances
for t in leg.get_texts():
    t.set_fontsize('small')    # the legend text fontsize

# matplotlib.lines.Line2D instances
for l in leg.get_lines():
    l.set_linewidth(1.5)  # the legend line width
plt.show()
In [ ]:
### Plotting using the OO interface and setting low level parameters
In [6]:
import matplotlib.pyplot as plt #1
figsize = (8, 5) #2 
fig = plt.figure(figsize=figsize) #3 
ax = fig.add_subplot(111) #4 
line = ax.plot(range(10))[0] #5 
ax.set_title('Plotted with OO interface') #6 
ax.set_xlabel('measured') 
ax.set_ylabel('calculated')
ax.grid(True) #7 
line.set_marker('o')
plt.savefig('oo.png',dpi=150)
plt.show()

Basic Pylab Boxplot

also see pandas.boxplot

In [7]:
import pandas as pd    
from pylab import boxplot as bp
plt.figure()
loansmin = pd.read_csv('../datasets/loanf.csv')
data = loansmin['FICO.Score']
arrdata = np.array(data)
print(data[1:3])
print("****")
print(type(arrdata))   
    # basic plot
b = bp(arrdata)
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-7-7f4c12b115be> in <module>()
----> 1 import pandas as pd
      2 from pylab import boxplot as bp
      3 plt.figure()
      4 loansmin = pd.read_csv('../datasets/loanf.csv')
      5 data = loansmin['FICO.Score']

/Users/nitin/anaconda/lib/python2.7/site-packages/pandas/__init__.pyc in <module>()
     39 import pandas.core.config_init
     40 
---> 41 from pandas.core.api import *
     42 from pandas.sparse.api import *
     43 from pandas.stats.api import *

/Users/nitin/anaconda/lib/python2.7/site-packages/pandas/core/api.py in <module>()
      7 from pandas.core.common import isnull, notnull
      8 from pandas.core.categorical import Categorical
----> 9 from pandas.core.groupby import Grouper
     10 from pandas.core.format import set_eng_float_format
     11 from pandas.core.index import Index, Int64Index, Float64Index, MultiIndex

/Users/nitin/anaconda/lib/python2.7/site-packages/pandas/core/groupby.py in <module>()
     13 from pandas.core.base import PandasObject
     14 from pandas.core.categorical import Categorical
---> 15 from pandas.core.frame import DataFrame
     16 from pandas.core.generic import NDFrame
     17 from pandas.core.index import Index, MultiIndex, _ensure_index

/Users/nitin/anaconda/lib/python2.7/site-packages/pandas/core/frame.py in <module>()
     38 import pandas.computation.expressions as expressions
     39 from pandas.computation.eval import eval as _eval
---> 40 from pandas.computation.scope import _ensure_scope
     41 from numpy import percentile as _quantile
     42 from pandas.compat import(range, zip, lrange, lmap, lzip, StringIO, u,

ImportError: No module named scope
In [10]:
import pandas as pd
cannot import name hashtable
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-10-af55e7023913> in <module>()
----> 1 import pandas as pd

/Users/nitin/anaconda/lib/python2.7/site-packages/pandas/__init__.py in <module>()
      4 
      5 try:
----> 6     from . import hashtable, tslib, lib
      7 except Exception:  # pragma: no cover
      8     import sys

ImportError: cannot import name hashtable