Line plots

4.2. Line plots#

The most common command of Matplotlib’s pyplot module is probably plt.plot. This function plots one or many series expressed either as standard Python lists, as NumPy Arrays or as Pandas DataFrames. For unidimensional data, it takes one list (y) or two lists (x, y) as arguments.

For exemple, to plot this list: [1.0, 2.0, -1.0, -0.0]:

import matplotlib.pyplot as plt

y = [1.0, 2.0, -1.0, -0.0]
plt.plot(y)

Fig. 4.2 A Matplotlib figure window.#

You should normally see the plot in a new window, as shown in Fig. 4.2. If, instead, you see the figure inline, or in Spyder’s Graph pane, or not at all, then you probably did not configure Matplotlib for interactive graphics. See Configuring Spyder.

The different buttons on the figure allow some interaction with the plot:

Icon

Function

Move the figure around (panning)

Zoom

Undo the last pan/zoom operation

Redo the last pan/zoom operation

Reset to the initial pan/zoom

Save the figure to an image file

By default, x starts at 0 and increments by 1 for each point. But we can also specify custom coordinates for x:

import matplotlib.pyplot as plt

y = [1.0, 2.0, -1.0, -0.0]
x = [0.0, 5.0, 10.0, 15.0]

plt.plot(x, y);
_images/55a0f0ebfe0a33b81934afcbca4b22df002b847419da45a85a95f2ee1bd2990f.png

The x values don’t have to be equidistant:

x = [0.0, 0.5, 1, 10]

plt.plot(x, y);
_images/14bf9f1d5373ece2b6377c4ecee92066f5ce28bcac888d9d790b8a85bc1a2189.png