In [1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

Basic Example


In [2]:
plt.plot([1,2,3,4])
plt.ylabel('[1,2,3,4] are considered on ordinate')
plt.xlabel('With no values for abscissa, py starts from 0 ')
plt.show()


Controlling Line and Axis properties


In [3]:
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^',
        linewidth = 1.0)


# plt.axis([0, 6, 0, 200])

## Alternative to axis function
# plt.xlim(-2,10)
#plt.ylim(-20,200)

plt.grid(False)
plt.show()


Multiple figures and subplots


In [4]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
x2 = np.arange(0.0, 5.0, 0.02)
y2 = np.cos(2 * np.pi * x2)

# Subplots
# subplot(n_rows, n_cols, index)

plt.subplot(3, 1, 1)
plt.plot(x1, y1, 'bo')

plt.subplot(313)
plt.plot(x2, y2, 'r--')

plt.show()


Multiple figures


In [5]:
plt.figure(1)
#plt.subplot(3,3,1)
plt.plot(x1, y1, 'bo')

plt.figure(2)
#plt.subplot(3,2,2)
plt.plot(x2, y2, 'k')

plt.show()


Labels and Text


In [6]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

plt.plot(x1, y1, 'bo', x1, y1, 'k--')    # k for black
plt.xlabel('Abscissa', fontsize = 10, color = 'b')
plt.ylabel('Ordinate')
plt.title('Figure Title')
plt.suptitle("Main heading",
            fontsize = 14,
            fontweight = 'bold')

# TeX symbols available at
# https://matplotlib.org/1.5.3/users/mathtext.html

plt.text(1, .4, r'$\theta=60 \degree$') # TeX

plt.annotate('2nd crest', xy=(2, 0.17), 
            xytext=(2.5, -0.3),
           arrowprops=dict(facecolor='green', 
                           shrink=0.02),)

plt.grid(True)
plt.show()


Misc Labelling


In [7]:
x = np.array([1,1,1,1,2,3,4,4,4,4,3,2,1])
y = np.array([1,2,3,4,4,4,4,3,2,1,1,1,1])

plt.plot(x,y)

# ha (align X-value) -> [center | right | left]
# va (align Y-value) -> [center | top | bottom]
plt.text(3.9,1.05,'Text1',
        ha = 'right',
        verticalalignment = 'bottom',
        rotation = 'horizontal'
        )

plt.text(4,2.5,'Text2',
        horizontalalignment = 'right',
        va = 'center',
        rotation = 'vertical'
        )

plt.text(1,4,'Text3 \n next line',
        horizontalalignment = 'left',
        verticalalignment = 'top',
        rotation = 45
        )


Out[7]:
<matplotlib.text.Text at 0x1a6e00eda0>

Text box


In [8]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

fig, ax = plt.subplots(1)
#print(ax)
ax.plot(x1, y1)
plt.text(0.65, 0.85, r'$\lambda = 2, \alpha = 5$',
        transform = ax.transAxes,  # makes width and height in percentage
        va = 'top',
        bbox = dict(
                boxstyle = 'round',
                facecolor = 'wheat',
                alpha = 0.78))  # alpha -> transparency

fig.show()


C:\Anaconda\lib\site-packages\matplotlib\figure.py:403: UserWarning: matplotlib is currently using a non-GUI backend, so cannot show the figure
  "matplotlib is currently using a non-GUI backend, "

Non-uniform scale/axis


In [9]:
x1 = np.arange(0.0, 1000.0, 0.5)
y1 = np.log10(x1)

plt.subplot(211)
plt.plot(x1, y1)
plt.yscale('linear')
plt.title('Linear Scale')

plt.subplot(212)
plt.plot(x1, y1)
plt.yscale('log')
plt.title('Log Scale')
plt.tight_layout()


C:\Anaconda\lib\site-packages\ipykernel_launcher.py:2: RuntimeWarning: divide by zero encountered in log10
  

Legend


In [10]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
x2 = np.arange(0.0, 5.0, 0.02)
y2 = np.cos(2 * np.pi * x2)

plt.plot(x1, y1, 'o-', label = "Legend I")
plt.plot(x2, y2, '.-', label = "Legend II")
#plt.axis([0, 5.5, -1, 1.5])

plt.legend(loc = 'best',    # upper left
          shadow = True,
          fontsize = 'medium',
          framealpha = 0.5)    # transperancy


Out[10]:
<matplotlib.legend.Legend at 0x1a6ca64a20>

Ticks


In [11]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x1, y1)

for tick in ax.yaxis.get_major_ticks():
   tick.label1On = False
   tick.label2On = True
   tick.label2.set_color('green')

for tick in ax.xaxis.get_major_ticks():
   tick.label1On = False
   tick.label2On = True
   tick.label2.set_color('red')


Dynamic Subplots


In [12]:
x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

plt.figure(0)
# similar to subplot(3,3,1)
# making 3 * 3 canvas space and assigning subplots
# at values like (0,0)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax1.plot(x1,y1)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax2.plot(x1,y1)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax3.plot(x1,y1)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax4.plot(x1,y1)
ax5 = plt.subplot2grid((3,3), (2, 1))
ax5.plot(x1,y1)
# Adjust spaces between subplots
plt.tight_layout()
plt.show()


Shadow


In [13]:
import matplotlib.patheffects as pe

x1 = np.arange(0.0, 5.0, 0.1)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

plt.plot(x1, y1, linewidth = 5,
        path_effects = [pe.SimpleLineShadow(),
                        pe.Normal()])
   
plt.text(3, 0.8, "Hello World!",
        path_effects = [pe.withSimplePatchShadow()])
   
plt.show()


Plots

Histogram


In [14]:
plt.hist(np.random.randn(1000),
#          bins=20,  # Number of bins, by default 10
         facecolor = 'green',
         alpha = 0.5)


Out[14]:
(array([  2.,   1.,  44., 110., 197., 268., 241.,  91.,  36.,  10.]),
 array([-3.76170018, -3.09090305, -2.42010592, -1.74930879, -1.07851165,
        -0.40771452,  0.26308261,  0.93387974,  1.60467688,  2.27547401,
         2.94627114]),
 <a list of 10 Patch objects>)

Bar charts

Vertical bar charts


In [15]:
n_grps = np.arange(5)
bar_width = 0.4

var1 = [20, 30, 10, 50, 90]
err1 = [2, 3, 4, 5, 4]

var2 = [10, 123, 19, 60, 40]
err2 = [1, 6, 2, 8, 7]

plt.bar(n_grps, var1, bar_width,
                alpha = 0.2,
                color = 'b',
                yerr = err1,
                error_kw = {'ecolor': '0.1'},
                label='Var1')

# bar_width is imp. to pass else both bars overlap
plt.bar(n_grps + bar_width, var2, bar_width,
                alpha = 0.5,
                color = 'r',
                yerr = err2,
                error_kw = {'ecolor': '0.5'},
                label='Var2')

plt.legend(loc = "upper left")
plt.xticks(n_grps + bar_width, 
          ('A', 'B', 'C', 'D', 'E'))


Out[15]:
([<matplotlib.axis.XTick at 0x1a6e0843c8>,
  <matplotlib.axis.XTick at 0x1a6e02d0f0>,
  <matplotlib.axis.XTick at 0x1a6e0c7240>,
  <matplotlib.axis.XTick at 0x1a6e04c198>,
  <matplotlib.axis.XTick at 0x1a6cf82da0>],
 <a list of 5 Text xticklabel objects>)

Horizontal bar charts


In [16]:
n_grps = np.arange(5)
bar_width = 0.4

var1 = [20, 30, 10, 50, 90]
err1 = [2, 3, 4, 5, 4]

plt.barh(n_grps, var1, bar_width,
        alpha = 0.5,
        color = 'b',
        xerr = err1,
        label = 'Var1')

plt.legend(loc = 'best')
plt.yticks(n_grps + (bar_width)/2, 
          ('A', 'B', 'C', 'D', 'E'))


Out[16]:
([<matplotlib.axis.YTick at 0x1a6e27cc18>,
  <matplotlib.axis.YTick at 0x1a6e285e48>,
  <matplotlib.axis.YTick at 0x1a6e09e128>,
  <matplotlib.axis.YTick at 0x1a6e30b710>,
  <matplotlib.axis.YTick at 0x1a6e310128>],
 <a list of 5 Text yticklabel objects>)

Pie Chart


In [17]:
names = ['Summer', 'Autumn', 'Spring', 'Winter']
percent = [15, 30, 45, 10]
colors = ['gold', 'lightcoral', 
         'yellowgreen', 'lightskyblue']
explode = (0, 0, 0, 0)  # takes out only the 3rd slice 

plt.pie(percent, explode = explode,
       labels = names, colors = colors,
       autopct='%.2f%%',   # display value
       shadow=True,
       startangle=90)
# Set aspect ratio to be equal so that 
# pie is drawn as a circle.
plt.axis('equal')


Out[17]:
(-1.1143898348979537, 1.12995579546176, -1.1258468317413044, 1.101230806657754)

Scatter plot

Single type of value


In [18]:
x = np.random.randn(100)
y = np.random.randn(100) * 1.7

plt.scatter(x, y, c = (0.2, 0.5, 0.3))
plt.show()


Multiple value


In [19]:
fig, ax = plt.subplots()
for color in ['red', 'black', 'yellow']:
   n = 50
   x, y = np.random.rand(2,n)
   ax.scatter(x, y, c = color, alpha = 0.5)
   
plt.show()


Box plot


In [20]:
plt.boxplot([np.linspace(0,60,30)])
plt.show()


With outliers


In [21]:
plt.boxplot(np.concatenate((
               np.random.rand(50)*100,
               np.ones(25)*50,
               np.random.rand(10)*100+100,
               np.random.rand(10)*-100),
               axis = 0))
   
plt.show()



In [ ]: