Python matplotlib

In brief #

  1. Define data within plot.plot(). Repeat if plotting multiple sources of data on the same plot. Order sequentially.

  2. Customize.

  3. Show (plt.show()) or save (plt.savefig('<filename>.png')).

Module #

from matplotlib import pyplot as plt

plot() #

A simple example:

x_vals = ['<some list of numbers>'] # x-axis
y_vals = ['<some list of numbers>'] # y-axis

# generate the plot
# this doesn't actually show the plot
plt.plot(x_vals, y_vals)

# explicitly show the plot
plt.show()

Multiples #

Can plot multiple categories of data on the same plot.

plt.plot(x_vals, y_vals)
plt.plot(x_vals, another_set_of_y_vals)

plt.show() # shows a single plot with two sources of data

Note that lines are ordered in the sequence they get added.

Format string #

String to specify marker, line, color. Add to plt.plot() as a parameter.

For details, see notes.

Condensed approach:

plt.plot(x_vals, y_vals, 'k--') # black dashed line, where k is black, double dashes is a dashed line
plt.plot(x_vals, another_set_of_y_vals, 'b') # blue line, default is a solid line

Expanded approach:

plt.plot(x_vals, y_vals, color='k', linestype='--', marker='o') # o is a larger marker
plt.plot(x_vals, another_set_of_y_vals, color='b')

Colors can also be expressed in hex values.

Line width #

plt.plot(x, y, linewidth=<integer>)

Subplots #

Customization #

Grid #

plt.grid(True)

Labels #

# title
plt.title('<some text>')

# x-axis
plt.xlabel('<some text>')

# y-axis
plt.ylabel('<some text>')

Limits #

x-limit

plt.xlim([<lower bound>, <upper bound>])

Legend #

With multiple categories, it’s usually helpful to add a legend.

plt.plot(x_vals, y_vals, label ='<legend text>')
plt.plot(x_vals, another_set_of_y_vals, label = '<legend text2>')

plt.legend() # leave this empty if the plt itself has 
plt.show() # shows a single plot with two sources of data

Here’s an approach where the legend is separated from the element. This does happen, but I think it’s brittle and prone to error.

plt.legend(['<legend text>', '<legend text2>'])

Padding #

plt.tight_layout()

Styles #

# get listing of available styles
print(plt.style.available)

# use specific available style
plt.style.use('fivethirtyeight')

There’s also an xkcd() style method.

plt.xkcd()

Plot Types #

Area Plot #

Histograms #

Pie Charts #

Scatter Plots #

Stack Plots #

Time Series #

Saving #

Programmatically save image.

plt.savefig('<filename>.png')

Resources #