part of Course 133 Navigating Matplotlib
|
|
|
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.figure()
plt.plot(x_curve, y_curve)
plt.show()
This bit
- initializes the figure,
- draws the curve described by our x and y, and
- displays it on the screen.
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.figure()
plt.scatter(x_scatter, y_scatter)
plt.show()
Like before, this bit
- initializes the figure,
- plots each of the points described by our x's and y's, and
- displays the resulting plot on the screen.
And there you have your scatterplot! With just this little bit of Matplotlib, you already know enough to be dangerous.