IPython Interactive Computing and Visualization Cookbook, http://ipython-books.github.io
Import packages
import numpy as np
%matplotlib inline
import matplotlib
from matplotlib import pyplot as plt
from matplotlib import ticker
The package that make scientific use of Python possible
Main class: N-dimensional array ndarray
a = np.arange(10).reshape(2,5)
a
Attributes:
a.shape
a.ndim
a.dtype
Array creation:
b = np.array([1,2,3,4,5])
b
b[1:3]
b[1:4:2]
b[1::2]
a[0]
a[:,0]
c = a[:,:,np.newaxis]
c.shape
a[:,[0,2]]
x = (a % 2 == 0)
x
a[x] = 0
a
d = 2 * a
d
a + d
a * d
a.dot(d.T)
np.dot(a, d.T)
a**2
NumPy has redefined many mathematical functions to operate on arrays
np.sin(a)
a.sum()
a.sum(axis=0)
a.sum(axis=1)
z = np.arange(2*3*4).reshape(2,3,4)
z
z.sum(axis=1)
a.sum(axis=1, keepdims=True)
a + 2
e = np.array([1, 2]).reshape(2,1)
e
a + e
b
a + b
Do not write for
loops in Python!
The default plotting library in Python
There are others.
Matplotlib has two types of interfaces:
Module matplotlib.pyplot
Various states are preserved across function calls
x = np.linspace(0, 20, 100)
y = np.sin(x)
plt.plot(x, y, 'ro-')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Sin')
plt.grid(True);
plt.plot(x, np.sin(x), 'r', x, np.cos(x), 'b');
s = np.abs(np.random.randn(x.shape[0])) * 100
plt.scatter(x, y, c=y, s=s);
plt.subplot(1, 2, 1)
plt.plot(x, np.sin(x), 'r')
plt.subplot(1, 2, 2)
plt.plot(x, np.cos(x), 'b')
plt.subplots_adjust(wspace=0.4);
plt.plot(x, np.exp(-x))
plt.yscale('log')
plt.grid();
fig, ax = plt.subplots()
ax.plot(x, y, 'ro-')
ax.set_xlabel('x')
ax.set_ylabel('y', rotation=0)
ax.grid()
ax.set_title('Sin');
fig.savefig('sin.eps', bbox_inches='tight')
Images
img = matplotlib.image.imread('sin.png')
type(img)
plt.imshow(img, interpolation='bicubic')
plt.axis('off')
plt.gcf().set_size_inches(8, 8);
Matrices
a = np.random.randn(4, 4)
a
plt.matshow(a);
Customising tick marks
plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot(x, y, 'r.-')
ax.set_xlabel('x')
ax.set_ylabel('y', rotation=0)
ax.grid(True)
ax.set_title('Sin');
ax.xaxis.set_major_locator(ticker.MultipleLocator(5.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(1.0))
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.4))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.2))