In [1]:
%load_ext watermark

In [2]:
%watermark -u -v -d -p matplotlib,numpy


Last updated: 15/07/2014 

CPython 3.4.1
IPython 2.0.0

matplotlib 1.3.1
numpy 1.8.1

[More info](http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/ipython_magic/watermark.ipynb) about the `%watermark` extension


In [3]:
%matplotlib inline



Lineplots in matplotlib

Sections



Simple line plot


In [21]:
import matplotlib.pyplot as plt

x = [1, 2, 3]

y_1 = [50, 60, 70]
y_2 = [20, 30, 40]

plt.plot(x, y_1, marker='x')
plt.plot(x, y_2, marker='^')

plt.xlim([0, len(x)+1])
plt.ylim([0, max(y_1+y_2) + 10])
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')
plt.title('Simple line plot')
plt.legend(['sample 1', 'sample2'], loc='upper left')

plt.show()




Line plot with error bars


In [25]:
import matplotlib.pyplot as plt

x = [1, 2, 3]

y_1 = [50, 60, 70]
y_2 = [20, 30, 40]

y_1_err = [4.3, 4.5, 2.0] 
y_2_err = [2.3, 6.9, 2.1] 

x_labels = ["x1", "x2", "x3"]

plt.errorbar(x, y_1, yerr=y_1_err, fmt='-x')
plt.errorbar(x, y_2, yerr=y_2_err, fmt='-^')

plt.xticks(x, x_labels)
plt.xlim([0, len(x)+1])
plt.ylim([0, max(y_1+y_2) + 10])
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')
plt.title('Line plot with error bars')
plt.legend(['sample 1', 'sample2'], loc='upper left')

plt.show()




Line plot with x-axis labels and log-scale


In [24]:
import matplotlib.pyplot as plt

x = [1, 2, 3]

y_1 = [0.5,7.0,60.0]
y_2 = [0.3,6.0,30.0]



x_labels = ["x1", "x2", "x3"]

plt.plot(x, y_1, marker='x')
plt.plot(x, y_2, marker='^')

plt.xticks(x, x_labels)
plt.xlim([0,4])
plt.xlabel('x-axis label')
plt.ylabel('y-axis label')
plt.yscale('log')
plt.title('Line plot with x-axis labels and log-scale')
plt.legend(['sample 1', 'sample2'], loc='upper left')

plt.show()




Gaussian probability density functions


In [4]:
import numpy as np
from matplotlib import pyplot as plt
import math

def pdf(x, mu=0, sigma=1):
    """
    Calculates the normal distribution's probability density 
    function (PDF).  
        
    """
    term1 = 1.0 / ( math.sqrt(2*np.pi) * sigma )
    term2 = np.exp( -0.5 * ( (x-mu)/sigma )**2 )
    return term1 * term2


x = np.arange(0, 100, 0.05)

pdf1 = pdf(x, mu=5, sigma=2.5**0.5)
pdf2 = pdf(x, mu=10, sigma=6**0.5)

plt.plot(x, pdf1)
plt.plot(x, pdf2)
plt.title('Probability Density Functions')
plt.ylabel('p(x)')
plt.xlabel('random variable x')
plt.legend(['pdf1 ~ N(5,2.5)', 'pdf2 ~ N(10,6)'], loc='upper right')
plt.ylim([0,0.5])
plt.xlim([0,20])

plt.show()




Cumulative Plots



Cumulative Sum


In [25]:
import numpy as np
import matplotlib.pyplot as plt

A = np.arange(1, 11)
B = np.random.randn(10) # 10 rand. values from a std. norm. distr.
C = B.cumsum()

fig, (ax0, ax1) = plt.subplots(ncols=2, sharex=True, sharey=True, figsize=(10,5))

## A) via plt.step()

ax0.step(A, C, label='cumulative sum') # cumulative sum via numpy.cumsum()
ax0.scatter(A, B, label='actual values')
ax0.set_ylabel('Y value')
ax0.legend(loc='upper right')


## B) via plt.plot()

ax1.plot(A, C, label='cumulative sum') # cumulative sum via numpy.cumsum()
ax1.scatter(A, B, label='actual values')
ax1.legend(loc='upper right')

fig.text(0.5, 0.04, 'sample number', ha='center', va='center')
fig.text(0.5, 0.95, 'Cumulative sum of 10 samples from a random normal distribution', ha='center', va='center')

plt.show()




Absolute Count


In [6]:
import numpy as np
import matplotlib.pyplot as plt

A = np.arange(1, 11)
B = np.random.randn(10) # 10 rand. values from a std. norm. distr.

plt.figure(figsize=(10,5))


plt.step(np.sort(B), A) 
plt.ylabel('sample count')
plt.xlabel('x value')
plt.title('Number of samples at a certain threshold')

plt.show()




Colormaps


In [4]:
import numpy as np
import matplotlib.pyplot as plt


fig, (ax0, ax1) = plt.subplots(1,2, figsize=(14, 7))
samples = range(1,16)

# Default Color Cycle

for i in samples:
    ax0.plot([0, 10], [0, i], label=i, lw=3) 

# Colormap    
    
colormap = plt.cm.Paired
plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, len(samples))])

for i in samples:
    ax1.plot([0, 10], [0, i], label=i, lw=3) 
    
# Annotation    
    
ax0.set_title('Default color cycle')
ax1.set_title('plt.cm.Paired colormap')
ax0.legend(loc='upper left')
ax1.legend(loc='upper left')

plt.show()




Marker styles


In [4]:
import numpy as np
import matplotlib.pyplot as plt

markers = [

'.', # point
',', # pixel
'o', # circle
'v', # triangle down
'^', # triangle up
'<', # triangle_left
'>', # triangle_right
'1', # tri_down
'2', # tri_up
'3', # tri_left
'4', # tri_right
'8', # octagon
's', # square
'p', # pentagon
'*', # star
'h', # hexagon1
'H', # hexagon2
'+', # plus
'x', # x
'D', # diamond
'd', # thin_diamond
'|', # vline

]

plt.figure(figsize=(13, 10))
samples = range(len(markers))


for i in samples:
    plt.plot([i-1, i, i+1], [i, i, i], label=markers[i], marker=markers[i], markersize=10) 


# Annotation    
    
plt.title('Matplotlib Marker styles', fontsize=20)
plt.ylim([-1, len(markers)+1])
plt.legend(loc='lower right')


plt.show()




Line styles


In [13]:
import numpy as np
import matplotlib.pyplot as plt

linestyles = ['-.', '--', 'None', '-', ':']

plt.figure(figsize=(8, 5))
samples = range(len(linestyles))


for i in samples:
    plt.plot([i-1, i, i+1], [i, i, i], 
             label='"%s"' %linestyles[i], 
             linestyle=linestyles[i],
             lw=4
             ) 

# Annotation    
    
plt.title('Matplotlib line styles', fontsize=20)
plt.ylim([-1, len(linestyles)+1])
plt.legend(loc='lower right')


plt.show()



In [ ]: