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

In [2]:
%matplotlib inline
  • Numpy is the standard numeric package for Python. It lets you use typed C-style arrays to perform very fast linear algebra. Users of MATLAB will find many similarities in this package.

In [9]:
# numpy supports typed 'C-style' arrays
a = np.array([0,1,2])
print(a, a.dtype.name)

a = np.arange(9)  # Can create simple arrays quickly
print(a)
print(a.shape)  # Arrays have a shape which can be altered
print(a.reshape(3,3))  # Reshape doesn't affect 'a'
print(a)
a.resize(3,3)
print(a)  # Resize does affect 'a'

print(a*2)  # Operations are elementwise on numpy arrays


[0 1 2] int32
[0 1 2 3 4 5 6 7 8]
(9,)
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[0 1 2 3 4 5 6 7 8]
[[0 1 2]
 [3 4 5]
 [6 7 8]]
[[ 0  2  4]
 [ 6  8 10]
 [12 14 16]]
  • Numpy has an enormous number of functions for manipulating arrays so we won't go through them here. Always check to see if there's a function that does what you want.
  • Matplotlib is an almost direct translation of MATLAB's plotting library written in Python and it interfaces well with Scipy and Numpy. There are many other plotting libraries which provide different plotting functionality if you need it.

In [4]:
x = np.linspace(0, 3*np.pi, 500)  # linspace creates evenly spaced numbers in range.
plt.plot(x, np.sin(x**2)*np.exp(-0.5*x), 'b-')    # Can pass numpy arrays into plots
plt.title('Damped chirp')


Out[4]:
<matplotlib.text.Text at 0xb12f1e8c>

In [5]:
fig = plt.figure(figsize=(9,4.5))
ax1 = fig.add_subplot(1,2,1)
ax1.set_xlabel('some random numbers')
ax1.set_ylabel('more random numbers')
ax1.set_title("Random scatterplot")
plt.plot(np.random.normal(size=2500), np.random.normal(size=2500), 'r.')
ax2 = fig.add_subplot(1,2,2)
plt.hist(np.random.normal(size=2500), bins=15)
ax2.set_xlabel('sample')
ax2.set_ylabel('cumulative sum')
ax2.set_title("Normal distrubution")
plt.tight_layout()