Matplotlib

  • Python package from producing 2-dimensional figures.
  • Originally developed to imitate MATLAB graphics commands.
  • Divided into 3 parts
    • A set of top-level functions to imitate the MATLAB commands.
    • The set of classes managing figures, text, lines, plots, etc
    • Various backends that take care of rendering (e.g. PS, SVG, PNG, ...)
  • I'll mostly ignore the MATLAB imitating functions and work directly with the OO level.

A Simple Line Plot

import matplotlib.pyplot as plt

# Create some data to plot
x_data = [x/10.0 for x in range(0, 200)]
y_data = [pow(x, 1.6) for x in x_data]
# Create a Figure object.
fig = plt.figure(figsize=(5, 4))
# Create an Axes object.
ax = fig.add_subplot(1,1,1) # one row, one column, first plot
# Plot the data.
ax.plot(x_data, y_data, color="blue", linestyle="dashed", linewidth="3")
# Add a title.
ax.set_title("Simple Figure of $y=x^{1.6}$")
# Add some axis labels.
ax.set_xlabel("x")
ax.set_ylabel("y")
# Produce an image.
fig.savefig("lineplot.png")
lineplot.png

A Simple Scatter Plot

import matplotlib.pyplot as plt
import random

# Create some data to plot
num_datapoints = 100
x_data = [random.gauss(1, 4) for i in range(0, num_datapoints)]
y_data = [pow(x, 2) + random.gauss(0, 10) for x in x_data]
# Create a Figure object.
fig = plt.figure(figsize=(5, 4))
# Create an Axes object.
ax = fig.add_subplot(1,1,1) # one row, one column, first plot
# Plot the data.
ax.scatter(x_data, y_data, color="red", marker="^")
# Add a title.
ax.set_title("An Example Scatter Plot")
# Add some axis labels.
ax.set_xlabel("x")
ax.set_ylabel("y")
# Produce an image.
fig.savefig("scatterplot.png")
scatterplot.png

A Histogram

import matplotlib.pyplot as plt
import random

# Create some data to plot
num_datapoints = 1000
dataset1 = [random.gauss(1, 4) for i in range(0, num_datapoints)]
dataset2 = [random.gauss(8, 2) for i in range(0, num_datapoints)]
dataset3 = [random.gauss(-5, 2) for i in range(0, num_datapoints)]
# Create a Figure object.
fig = plt.figure(figsize=(5, 4))
# Create an Axes object.
ax = fig.add_subplot(1,1,1) # one row, one column, first plot
# Plot the data.
ax.hist((dataset1, dataset2), bins=20, color=("red", "green"))
ax.hist(dataset3, bins=20, color="blue")
# Add a title.
ax.set_title("An Example Histogram Plot")
# Add some axis labels.
ax.set_xlabel("x")
ax.set_ylabel("Frequency")
# Produce an image.
fig.savefig("histogramplot.png")
histogramplot.png

Other matplotlib stuff

  • add annotations
  • ticks, grids
  • multiple plots in figure, plots inside plots
  • interface with UI toolkits (wxpython, tkinter, qt, gtk, fltk and macosx)
    • associate events with clicks on objects etc