Chapter 26. Simple Line Plots

Perhaps the simplest of all plots is the visualization of a single function y = f ( x ) . Here we will take a first look at creating a simple plot of this type. As in all the following chapters, we’ll start by setting up the notebook for plotting and importing the packages we will use:

In [1]: %matplotlib inline
        import matplotlib.pyplot as plt
        plt.style.use('seaborn-whitegrid')
        import numpy as np

For all Matplotlib plots, we start by creating a figure and axes. In their simplest form, this can be done as follows (see Figure 26-1).

In [2]: fig = plt.figure()
        ax = plt.axes()

In Matplotlib, the figure (an instance of the class plt.Figure) can be thought of as a single container that contains all the objects representing axes, graphics, text, and labels. The axes (an instance of the class plt.Axes) is what we see above: a bounding box with ticks, grids, and labels, which will eventually contain the plot elements that make up our visualization. Throughout this part of the book, I’ll commonly use the variable name fig to refer to a figure instance and ax to refer to an axes instance or group of axes instances.

pdsh2 2601
Figure 26-1. An empty gridded axes

Once we have created an axes, we can use the ax.plot method to plot some data. Let’s start with a simple sinusoid, as shown in Figure 26-2.

In [3]: fig = plt.figure()
        ax = plt.axes()

        x = np.linspace(0, 10, 

Get Python Data Science Handbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.