Overview

The goal of this tutorial is to provide an overview of the use of Matplotlib. Matplotlib has a vast array of functionality, so this is by no means complete. For more information, try looking at the:

Matplotlib is a library that started as a way to get MATLAB-like plotting capabilities in Python. It has since evolved on its own, with a focus on publication-quality graphics. Some features

  • A variety of support GUI and non-interactive backends
  • Lines, scatter, bar
  • Contours, image, mesh
  • LaTeX-like math rendering
  • Animations
  • Basic 3D plotting

Basic Plotting

Matplotlib is a python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.


In [1]:
# Set-up to have matplotlib use its inline backend
%matplotlib inline

In [2]:
# Convention for import of the pyplot interface
import matplotlib.pyplot as plt
import numpy as np

In [3]:
# Create some example data
x = np.linspace(0, 2, 100)

In [4]:
# Go ahead and explicitly create a figure and an axes
fig, ax = plt.subplots(1, 1)

# Plot our x variable on the x-axis and x^2 on the y-axis
ax.plot(x, x**2)


Out[4]:
[<matplotlib.lines.Line2D at 0x10fa7b4e0>]

In [5]:
# Add some labels to the plot
ax.set_xlabel('x')
ax.set_ylabel('f(x)')

# Needed to reuse and see the updated plot while using inline
fig


Out[5]:

In [6]:
# Let's add a title with a bit of latex syntax
ax.set_title('$y = x^2$', fontdict={'size':22})

fig


Out[6]:

In [7]:
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)

# Plot a set of different polynomials.
# The label argument is used when generating a legend.
ax.plot(x, x, label='$x$')
ax.plot(x, x * x, label='$x^2$')
ax.plot(x, x**3, label='$x^3$')

# Add labels and title
ax.set_xlabel('x')
ax.set_ylabel('f(x)')
ax.set_title('Polynomials')

# Add gridlines
ax.grid(True)

# Add a legend to the upper left corner of the plot
ax.legend(loc='upper left')


Out[7]:
<matplotlib.legend.Legend at 0x111ca7c50>

Exercise

Make a plot containing:

  • 3 different plots with different styles. Suggestions:
    • sin, cos, tan
    • exp, log
    • sqrt
    • Any others you want to try
  • Use labels and a legend
  • Add labels and title