Matplotlib Tutorial

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

Line Plot

In [144]:
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
u = 1 + np.cos(2*np.pi*t)

# Note that using plt.subplots below is equivalent to using
# fig = plt.figure and then ax = fig.add_subplot(111)
fig, ax = plt.subplots(); # create a figure and a subplot

# Plot two lines
line1, = ax.plot(t, s);
line2, = ax.plot(t, u, 'b--');

# Setup labels and title
ax.set_xlabel('time (s)', size=18);
ax.set_ylabel('voltage (mv)', size = 18);
ax.set_title('About as simple as it gets, folks');

# Setup legend
# bbox_to_anchor, setup the location of legend
legend = ax.legend((line1, line2), ('sin', 'cos'), loc='upper left', shadow=True, facecolor='0.9', bbox_to_anchor=(0.01, 1));

# Setup ticks
ax.set_xticks(np.arange(10)*0.4);
ax.set_yticks(np.arange(14)*0.2)

# Setup limits
ax.set_xlim(0, 2);
ax.set_ylim(bottom=0)

# Setup grid
ax.grid(color='r', linestyle='-', linewidth=0.2)

plt.show()

plt.plot, line style

Axis Class

Text Class, parameters for labels and titles

Multiple subplots

In [104]:
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
u = 1 + np.cos(2*np.pi*t)

f, axs = plt.subplots(2, 2)

# Plot two lines
axs[0, 0].plot(t, s);
axs[0, 1].scatter(t, s);
axs[1, 0].plot(t, u, 'b--');
axs[1, 1].scatter(t, u);

plt.show()

Scatter Plot

In [108]:
x = np.random.randint(0, 100, size=40);
y = np.sin(x);

fig, ax = plt.subplots(); # create a figure and a subplot

volume = y*50; # setup size
ax.scatter(x, y, c=np.random.randint(0, 50, 40), s=volume, alpha=0.8);

plt.show()

Image

In [129]:
import matplotlib.image as mpimg
img=mpimg.imread('EA-02-1.png');
print img.ndim, img.shape; # row, column, panel
plt.imshow(img);
plt.show()
3 (450, 800, 3)
In [144]:
plt.imshow(img[:, :, 0], cmap='nipy_spectral'); # use a color map
plt.colorbar();
plt.show();
In [151]:
import matplotlib.cm as cm; # load color maps
import matplotlib.mlab as mlab # load MATLAB functions
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1  # difference of Gaussians

# interpolation, interpolation method
# cmap, color map
# origin, Place the [0,0] index in the upper left or lower left corner of the axes
# extent, range
im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn,
                origin='lower', extent=[-3, 3, -3, 3],
                vmax=abs(Z).max(), vmin=-abs(Z).max())

plt.show()

Contor Plot

In [170]:
dx, dy = 0.05, 0.05

# generate 2 2d grids for the x & y bounds
y, x = np.mgrid[slice(1, 5 + dy, dy),
                slice(1, 5 + dx, dx)]

z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)

fig, axs = plt.subplots(1, 2); # create a figure and a subplot
axs[0].pcolormesh(x, y, z, cmap=cm.PiYG, norm = plt.Normalize(0, 1))

axs[1].contourf(x, y, z, cmap=cm.PiYG, norm = plt.Normalize(0, 1))

plt.show();

Histogram Plot

In [18]:
import matplotlib.mlab as mlab

mu = 100  # mean of distribution
sigma = 15  # standard deviation of distribution
x = mu + sigma * np.random.randn(437)

num_bins = 50;

fig, ax = plt.subplots()

# the histogram of the data
# normed, False, each bin value is the number in that bin; True, form a probability density,
# the area (or integral) under the histogram will sum to 1
# n, the values of the histogram bins
# bins, the edges of the bins
n, bins, patches = ax.hist(x, num_bins, normed=True)

y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y);

plt.show()

Bar Chart

In [46]:
n_groups = 5

means_men = (20, 35, 30, 35, 27)
std_men = (2, 3, 4, 1, 2)

means_women = (25, 32, 34, 20, 25)
std_women = (3, 5, 2, 3, 3)

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.35

opacity = 0.4
error_config = {'ecolor': '0.4', 'capsize':2}

rects1 = ax.bar(index, means_men, bar_width,
                alpha=opacity, color='b',
                yerr=std_men, error_kw=error_config,
                label='Men')

rects2 = ax.bar(index + bar_width, means_women, bar_width,
                alpha=opacity, color='r',
                yerr=std_women, error_kw=error_config,
                label='Women')

ax.set_xticks(index + bar_width / 2)
ax.set_xticklabels(('A', 'B', 'C', 'D', 'E'))
ax.legend()

fig.tight_layout(); # automatically adjusts subplot params so that the subplot(s) fits in to the figure area
plt.show()

Pie Chart

In [58]:
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0.05, 0.1, 0.05, 0.1)  # only "explode" the 2nd slice (i.e. 'Hogs')

fig, ax = plt.subplots()
# explode, the fraction of the radius with which to offset each wedge
# startangle, rotates the start of the pie chart by angle degrees counterclockwise from the x-axis
ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)
ax.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

Streamplot Plot

In [15]:
w = 3
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

fig, ax = plt.subplots(); # create a figure and a subplot

ax.streamplot(X, Y, U, V, density=[0.5, 1])
plt.show()

Fill Plot

In [80]:
x = np.linspace(0, 1, 500)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)
fig, ax = plt.subplots()

ax.fill(x, y, zorder=10, alpha=0.8)
ax.grid();
plt.show();

Polar Plot

In [91]:
r = np.arange(0, 2, 0.01)
theta = 2 * np.pi * r

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)
ax.set_rticks([0.5, 1, 1.5, 2])
ax.set_rlabel_position(-22.5);
ax.grid(True);

plt.show()

3D Line Plot

In [7]:
fig = plt.figure()
ax = fig.gca(projection='3d')

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.plot(x, y, z)
plt.show()

3D Scatter Plot

In [12]:
fig = plt.figure()
ax = fig.gca(projection='3d')

theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)

ax.scatter(x, y, z)
plt.show()

3D Surface Plot

In [3]:
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z);
plt.show()

Customizing matplotlib

In [92]:
print(plt.style.available); # print out available styles
[u'seaborn-darkgrid', u'seaborn-notebook', u'classic', u'seaborn-ticks', u'grayscale', u'bmh', u'seaborn-talk', u'dark_background', u'ggplot', u'fivethirtyeight', u'_classic_test', u'seaborn-colorblind', u'seaborn-deep', u'seaborn-whitegrid', u'seaborn-bright', u'seaborn-poster', u'seaborn-muted', u'seaborn-paper', u'seaborn-white', u'seaborn-pastel', u'seaborn-dark', u'seaborn', u'seaborn-dark-palette']
In [96]:
with plt.style.context(('ggplot')):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
    plt.show()
In [94]:
with plt.style.context(('dark_background')):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
    plt.show()

Style with Cycler

In [113]:
from cycler import cycler
x = np.linspace(0, 2 * np.pi, 50)
offsets = np.linspace(0, 2 * np.pi, 4, endpoint=False)
yy = np.transpose([np.sin(x + phi) for phi in offsets])
default_cycler = cycler('color', ['r', 'g', 'b', 'y']) \
                    + cycler('linestyle', ['-', '--', ':', '-.'])

plt.rc('lines', linewidth=4)
plt.rc('axes', prop_cycle=default_cycler)

custom_cycler = cycler('color', ['c', 'm', 'y', 'k']) \
    + cycler('lw', [1, 2, 3, 4])

fig, (ax0, ax1) = plt.subplots(nrows=2)
ax0.plot(yy)
ax0.set_title('Set default color cycle to rgby')
ax1.set_prop_cycle(custom_cycler)
ax1.plot(yy)
ax1.set_title('Set axes color cycle to cmyk')

# Add a bit more space between the two plots.
fig.subplots_adjust(hspace=0.3)
plt.show()
(4,) (50, 4)