part of Course 133 Navigating Matplotlib

thumbnail of line plot of a sinc function
plt.plot(x, y)
thumbnail of scatter plot showing a trend
plt.scatter(x, y)

Shortcut to plotting in Matplotlib

Matplotlib has a well deserved reputation for being a labyrinth. It has dark twisted passageways. Some lead to dead ends. It also has shortcuts to glory and freedom. In this series I’ll help you get where you want to go as directly as I know how, while steering clear of horned monsters.

Part of Matplotlib is a simplified interface called pyplot that doesn't require you to know about the innards of the system. For the most common tasks, it gives a convenient set of commands. We'll take advantage of it.

import numpy as np
import matplotlib.pyplot as plt

To use pyplot in a script, first we import it. We also import numpy, a numerical processing library that is great for working with data of any sort.

Plotting curves

The most common thing to do in Matplotlib is plot a line. First we have to create one.

x_curve = np.linspace(-2 * np.pi, 2 * np.pi, 500)
y_curve = np.sinc(x_curve)

We create the x values for our curve using numpy's linspace() function. The way we called it, it returns an array of 500 evenly spaced values between -2 pi and 2 pi.

Then we create the y values using numpy's sinc() function. It's a curve with some personality, so it illustrates the plotting quite well.

plt.plot(x_curve, y_curve)

This bit

  1. initializes the figure,
  2. draws the curve described by our x and y, and
  3. displays it on the screen.

curve plot of a sinc function

And that's it! You just plotted a curve in python. One of the very best things about Matplotlib is how it streamlines common tasks. Once we had our data, it only took three lines of code to make a plot.

Plotting points

The second most common plotting task is show points in a scatter plot. This is streamlined too.

x_scatter = np.linspace(-1, 1)
y_scatter = x_scatter + np.random.normal(size=x_scatter.size)

The first step again is create some fake data. Here we generate some evenly-spaced x values between -1 and 1 and make some y values that are similar, but have some normally-distributed random noise added to them (zero mean and unit variance).

plt.scatter(x_scatter, y_scatter)

Like before, this bit

  1. initializes the figure,
  2. plots each of the points described by our x's and y's, and
  3. displays the resulting plot on the screen.

scatter plot of points showing an upward trend

And there you have your scatterplot! With just this little bit of Matplotlib, you already know enough to be dangerous.