Simple Line Plots _ Python Data Science Handbook
Simple Line Plots _ Python Data Science Handbook
do) by Jake
VanderPlas; Jupyter notebooks are available on GitHub (https://github.com/jakevdp/PythonDataScienceHandbook).
Open in Colab
(https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/note
Simple-Line-Plots.ipynb)
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 with all the
following sections, we'll start by setting up the notebook for plotting and
importing the packages we will use:
For all Matplotlib plots, we start by creating a figure and an axes. In their simplest
form, a figure and axes can be created as follows:
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 and labels, which will eventually contain the
plot elements that make up our visualization. Throughout this book, we'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.
Once we have created an axes, we can use the ax.plot function to plot some
data. Let's start with a simple sinusoid:
Alternatively, we can use the pylab interface and let the figure and axes be
created for us in the background (see Two Interfaces for the Price of One (04.00-
introduction-to-matplotlib.html#Two-Interfaces-for-the-Price-of-One) for a
discussion of these two interfaces):
If we want to create a single figure with multiple lines, we can simply call the
plot function multiple times:
In [5]: plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x));
That's all there is to plotting simple functions in Matplotlib! We'll now dive into
some more details about how to control the appearance of the axes and lines.
The first adjustment you might wish to make to a plot is to control the line colors
and styles. The plt.plot() function takes additional arguments that can be used
to specify these. To adjust the color, you can use the color keyword, which
accepts a string argument representing virtually any imaginable color. The color
can be specified in a variety of ways:
Similarly, the line style can be adjusted using the linestyle keyword:
In [7]: plt.plot(x, x + 0, linestyle='solid')
plt.plot(x, x + 1, linestyle='dashed')
plt.plot(x, x + 2, linestyle='dashdot')
plt.plot(x, x + 3, linestyle='dotted');
If you would like to be extremely terse, these linestyle and color codes can be
combined into a single non-keyword argument to the plt.plot() function:
These single-character color codes reflect the standard abbreviations in the RGB
(Red/Green/Blue) and CMYK (Cyan/Magenta/Yellow/blacK) color systems,
commonly used for digital color graphics.
There are many other keyword arguments that can be used to fine-tune the
appearance of the plot; for more details, I'd suggest viewing the docstring of the
plt.plot() function using IPython's help tools (See Help and Documentation in
IPython (01.01-help-and-documentation.html)).
# Adjusting the Plot: Axes Limits
Matplotlib does a decent job of choosing default axes limits for your plot, but
sometimes it's nice to have finer control. The most basic way to adjust axis limits
is to use the plt.xlim() and plt.ylim() methods:
plt.xlim(-1, 11)
plt.ylim(-1.5, 1.5);
If for some reason you'd like either axis to be displayed in reverse, you can simply
reverse the order of the arguments:
plt.xlim(10, 0)
plt.ylim(1.2, -1.2);
The plt.axis() method goes even beyond this, allowing you to do things like
automatically tighten the bounds around the current plot:
For more information on axis limits and the other capabilities of the plt.axis
method, refer to the plt.axis docstring.
# Labeling Plots
As the last piece of this section, we'll briefly look at the labeling of plots: titles,
axis labels, and simple legends.
Titles and axis labels are the simplest such labels—there are methods that can be
used to quickly set them:
The position, size, and style of these labels can be adjusted using optional
arguments to the function. For more information, see the Matplotlib
documentation and the docstrings of each of these functions.
When multiple lines are being shown within a single axes, it can be useful to
create a plot legend that labels each line type. Again, Matplotlib has a built-in way
of quickly creating such a legend. It is done via the (you guessed it) plt.legend()
method. Though there are several valid ways of using this, I find it easiest to
specify the label of each line using the label keyword of the plot function:
In [15]: plt.plot(x, np.sin(x), '-g', label='sin(x)')
plt.plot(x, np.cos(x), ':b', label='cos(x)')
plt.axis('equal')
plt.legend();
As you can see, the plt.legend() function keeps track of the line style and color,
and matches these with the correct label. More information on specifying and
formatting plot legends can be found in the plt.legend docstring; additionally,
we will cover some more advanced legend options in Customizing Plot Legends
(04.06-customizing-legends.html).
plt.xlabel() → ax.set_xlabel()
plt.ylabel() → ax.set_ylabel()
plt.xlim() → ax.set_xlim()
plt.ylim() → ax.set_ylim()
plt.title() → ax.set_title()
Open in Colab
(https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/note
Simple-Line-Plots.ipynb)