matplotlib Quick Ref

Preliminaries

To import matplotlib, the recommended way is:

import matplotlib.pyplot as plt

Basic Plotting with plt

The imported plt can be used for interactive and basic usage, similar to MATLAB. A typical workflow might be:

  1. Assemble your data
  2. Create a plot using one of the plot types
  3. Add options, legends, axes configurations, annotations using plt.* methods
  4. Call plt.show() to show the plot (may or may not be needed depending on the environment/software you are using)

See here for the full list of methods and API.

Some Common Methods

Plot types

  • plt.plot
  • plt.bar
  • plt.pie

Annotations

  • plt.axhline, plt.axvline
  • plt.arrow
  • plt.annotate, plt.text
  • plt.title

Axis

  • plt.xlabel, plt.ylabel
  • plt.xticks, plt.yticks
  • plt.xlim, plt.ylim

Object Approach

This approach is initiated by calling the subplots() function with returns separated Figure and Axes objects, allowing direct access to each respective object:

fig, ax = plt.subplots()

This function also allows separate figures and multi-axis figures to be created and assigned to separate variables:

fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()

Additionally, multiple axes (i.e. plots) in one figure can be created with ncols and nrows:

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)

Use the sharey and sharex arguments to share x or y axes between subplots:

fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharey=True)

Plot calls may then be used on the Axes object:

ax1.plot(x,y)

To save the plot to a file:

fig1.savefig('my_figure.png')

To show the plot, call plt.show() or fig1.show() - which one is preferable depends on the environment and context you are using as explained here2. Also, depending on your environment these may not not be needed at all (such as in iPython/Jupyter).

Configuring

Color, linestyle, linewidth, and other properties of the plot can be specified in the plot call.

See here3 for a full list of options.

Options

Property Keyword argument
Line color color or c
Line width linewidth or lw
Line style linestyle or ls
Marker style marker

Colors

Colors may be entered in a variety of ways - string name, RGB tuple, HEX string, etc. A range of color names are included in matplotlib by default. Basic colors are available in addition to those named in the X window system and the xkcd color survey.

Basic colors include: blue/ b, green/ g, red/r, cyan/ c, magenta/ m, yellow/ y, black/ k, white/ w.

Legend

Add a legend by calling ax.legend(). For the legend to have names, labels are typically first specified in the plot call with the legend keyword argument:

ax1.plot(t, v, legend='Velocity')

Alternatively, if you store a reference or get the line object from an existing axes, you can call:

line.set_label(str)

Then, when calling ax.legend() the legend generator knows names for each line. These methods are preferred since the names and data are linked together.

Placement of the legend can be set to 9 points forming a grid pattern over the axes, by setting the loc argument to a combination of upper, lower, left, right, center (for example upper left). center only places it in the middle of both directions. best places the legend in the area with the minimum amount of overlap with other elements.

See the API for the many other available options.

Other Things

Grids

Turning on grids can be achieved with:

ax.grid(True, which='both')

The which argument specifies which axis to turn them on for (x, y, or both).

Styles

There are some predefined styles to use in your plots. The style names for these include:

  • Solarize_Light2
  • _classic_test_patch
  • bmh
  • classic
  • dark_background
  • fast
  • fivethirtyeight
  • ggplot
  • grayscale
  • seaborn
  • seaborn-bright
  • seaborn-colorblind
  • seaborn-dark
  • seaborn-dark-palette
  • seaborn-darkgrid
  • seaborn-deep
  • seaborn-muted
  • seaborn-notebook
  • seaborn-paper
  • seaborn-pastel
  • seaborn-poster
  • seaborn-talk
  • seaborn-ticks
  • seaborn-white
  • seaborn-whitegrid
  • tableau-colorblind10

A style can be turned in your session via:

plt.style.use(<name>)

To activate a style for just a specific plot, you can use the with mechanism:

with plt.style.context(<name>):
    plt.plot(x,y)

Or,

with plt.style.context(<name>):
    fig,ax = plt.subplots()
    ax.plot(x,y)

Square/1:1 plots

Use Axes.set_aspect('equal') to make the axes scales have a 1:1 ratio.