Matplotlib: plotting#

Authors: Nicolas Rougier, Mike Müller, Gaël Varoquaux

Introduction#

Matplotlib is probably the most used Python package for 2D-graphics. It provides both a quick way to visualize data from Python and publication-quality figures in many formats. We are going to explore matplotlib in interactive mode covering most common cases.

IPython, Jupyter, and matplotlib modes#

The Jupyter notebook and the IPython enhanced interactive Python, are tuned for the scientific-computing workflow in Python, in combination with Matplotlib:

For interactive matplotlib sessions, turn on the matplotlib mode.

IPython sessions#

To make plots open interactively in an IPython console session use the following magic command:

%matplotlib
Using matplotlib backend: module://matplotlib_inline.backend_inline

Jupyter notebook#

The Jupyter Notebook uses Matplotlib mode by default; that is, it inserts the figures into the notebook, as you run Matplotlib commands.

pyplot#

pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is modeled closely after Matlab™. Therefore, the majority of plotting commands in pyplot have Matlab™ analogs with similar arguments. Important commands are explained with interactive examples.

import matplotlib.pyplot as plt

Simple plot#

In this section, we want to draw the cosine and sine functions on the same plot. Starting from the default settings, we’ll enrich the figure step by step to make it nicer.

First step is to get the data for the sine and cosine functions:

import numpy as np

X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)

X is now a numpy array with 256 values ranging from \(-\pi\) to \(+\pi\) (included). C is the cosine (256 values) and S is the sine (256 values).

To run the code, you can execute it in a Jupyter notebook or type it in an IPython interactive session:

$ ipython --matplotlib

This brings us to the IPython prompt:

IPython 0.13 -- An enhanced Interactive Python.
?       -> Introduction to IPython's features.
%magic  -> Information about IPython's 'magic' % functions.
help    -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.

Plotting with default settings#

Hint

Documentation

import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)

plt.plot(X, C)
plt.plot(X, S);
../../_images/adcf0f5425b31026fadb8a85f6106f59c9210069314ccc4da0b901886b822dc6.png

Note

You will notice that we used a semicolon (;) to end the last line in the cell above. This is to prevent Jupyter or IPython echoing the return value of this final expression back to us in the notebook or console session. It has no other effect; it does not affect the execution of the code.

Instantiating defaults#

Hint

Documentation

In the plotting code below, you will see that we’ve instantiated (and commented) all the figure settings that influence the appearance of the plot.

import numpy as np
import matplotlib.pyplot as plt

# Create a figure of size 8x6 inches, 80 dots per inch
plt.figure(figsize=(8, 6), dpi=80)

# Create a new subplot from a grid of 1x1
plt.subplot(1, 1, 1)

X = np.linspace(-np.pi, np.pi, 256)
C, S = np.cos(X), np.sin(X)

# Plot cosine with a blue continuous line of width 1 (pixels)
plt.plot(X, C, color="blue", linewidth=1.0, linestyle="-")

# Plot sine with a green continuous line of width 1 (pixels)
plt.plot(X, S, color="green", linewidth=1.0, linestyle="-")

# Set x limits
plt.xlim(-4.0, 4.0)

# Set x ticks
plt.xticks(np.linspace(-4, 4, 9))

# Set y limits
plt.ylim(-1.0, 1.0)

# Set y ticks
plt.yticks(np.linspace(-1, 1, 5));

# You could also save this figure using 72 dots per inch with:
# plt.savefig("exercise_2.png", dpi=72)
../../_images/02198bd2486675603f65ca225557c954a96a6c06d63b52b34f4c3cfdfe0ef2f6.png

Changing colors and line widths#

Hint

Documentation

# Generate the plot.
plt.figure(figsize=(10, 6), dpi=80)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-");

# Get the current figure (gcf) into a variable for later use.
fig_to_update = plt.gcf()
../../_images/5e439a09c5a4975f98999530aa23fcc955571a758a1710c146360e8a3b883e05.png

Setting limits#

Hint

Documentation

  • xlim() command

  • ylim() command

# Restore previous figure, ready to update below.
plt.figure(fig_to_update)

# Setting the axis limits.
plt.xlim(X.min() * 1.2, X.max() * 1.2)
plt.ylim(C.min() * 1.2, C.max() * 1.2)

# Make Jupyter display updated figure.
fig_to_update
../../_images/0bc1ec628b7774b71f50e6a16292494b79cb61420418b353162d9f24b8948736.png

Setting ticks#

Hint

Documentation

# Restore figure we are working on.
plt.figure(fig_to_update)

# Set x and y ticks.
plt.xticks([-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi])
plt.yticks([-1, 0, +1])

# Make Jupyter display updated figure.
fig_to_update
../../_images/97e5b2864b848f768307eb516629b3e28cbba3935d10250838cd28a3770badc2.png

Setting tick labels#

Hint

Documentation

# Restore figure
plt.figure(fig_to_update)

# Update tick labels.
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
          [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])

plt.yticks([-1, 0, +1],
          [r'$-1$', r'$0$', r'$+1$'])

# Force display of updated figure.
fig_to_update
../../_images/bcd815bc4bf7b43f62121900852f2f6e80c804a5e5cdb0873a7d12ec8b94762c.png

Moving spines#

# Restore figure
plt.figure(fig_to_update)

# Update spines.
ax = plt.gca()  # gca stands for 'get current axis'
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

# Force display of updated figure.
fig_to_update
../../_images/605ba4abc9a04c03d4efac26ab85e27ade68fec671d753d51114effef334ca1c.png

Adding a legend#

Hint

Documentation

# Restore figure
plt.figure(fig_to_update)

# Add legend.
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="cosine")
plt.plot(X, S, color="red",  linewidth=2.5, linestyle="-", label="sine")

plt.legend(loc='upper left')

# Force display of updated figure.
fig_to_update
../../_images/64bb3eab30af8ef431b5ee43820bef7212052c10f3bac0c2f27afd73bc9924c4.png

Annotate some points#

Hint

Documentation

# Restore figure
plt.figure(fig_to_update)

# Annotate points.
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')

plt.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
             xy=(t, np.cos(t)), xycoords='data',
             xytext=(-90, -50), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

plt.plot([t, t],[0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")
plt.scatter([t, ],[np.sin(t), ], 50, color='red')

plt.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
             xy=(t, np.sin(t)), xycoords='data',
             xytext=(+10, +30), textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

# Force display of updated figure.
fig_to_update
../../_images/2456f0d4177137e519ef1151ef117474d777f17f49cbb74526d457515cba3964.png

Devil is in the details#

Hint

Documentation

# Restore figure
plt.figure(fig_to_update)

# Set properties of tick labels.
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(16)
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))

# Force display of updated figure.
fig_to_update
../../_images/2c7ef337351693ca3ed725dd80f38083c4686f5e686e1e3caad74b6f0206ad22.png

Figures, Subplots, Axes and Ticks#

A “figure” in matplotlib means the whole window in the user interface. Within this figure there can be “subplots”.

Figures#

Argument

Default

Description

num

1

number of figure

figsize

figure.figsize

figure size in inches (width, height)

dpi

figure.dpi

resolution in dots per inch

facecolor

figure.facecolor

color of the drawing background

edgecolor

figure.edgecolor

color of edge around the drawing background

frameon

True

draw figure frame or not

# Useful working in a GUI outside the notebook.
plt.close(1)     # Closes figure 1

Subplots#

Hide code cell source

plt.figure(figsize=(6, 4))
plt.subplot(2, 1, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,1,1)", ha="center", va="center", size=24, alpha=0.5)

plt.subplot(2, 1, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,1,2)", ha="center", va="center", size=24, alpha=0.5)
# Title for whole figure (rather than current subplot).
plt.suptitle('Horizontal subplots')

plt.tight_layout()
../../_images/8a36775b9184568ce07e557c1a7566be17e61b9bbee744b87211d63a7a13756a.png

Hide code cell source

plt.figure(figsize=(6, 4))
plt.subplot(1, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,1)", ha="center", va="center", size=24, alpha=0.5)

plt.subplot(1, 2, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(1,2,2)", ha="center", va="center", size=24, alpha=0.5)
plt.suptitle('Vertical subplots')

plt.tight_layout()
../../_images/dfe1bf7bb330d18e30cbce8ff172130b80a1e51e26212a2c44309eb46d88620e.png

Hide code cell source

plt.figure(figsize=(6, 4))
plt.subplot(2, 2, 1)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,1)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 2)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,2)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 3)
plt.xticks([])
plt.yticks([])

plt.text(0.5, 0.5, "subplot(2,2,3)", ha="center", va="center", size=20, alpha=0.5)

plt.subplot(2, 2, 4)
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "subplot(2,2,4)", ha="center", va="center", size=20, alpha=0.5)
plt.suptitle('Subplot grid')

plt.tight_layout()
../../_images/9ae43cc3972c8d96145dcc0462e924993ced52d377fbbc3274056e653d78f33b.png

Hide code cell source

from matplotlib import gridspec

plt.figure(figsize=(6, 4))
G = gridspec.GridSpec(3, 3)

axes_1 = plt.subplot(G[0, :])
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 1", ha="center", va="center", size=24, alpha=0.5)

axes_2 = plt.subplot(G[1, :-1])
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 2", ha="center", va="center", size=24, alpha=0.5)

axes_3 = plt.subplot(G[1:, -1])
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 3", ha="center", va="center", size=24, alpha=0.5)

axes_4 = plt.subplot(G[-1, 0])
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 4", ha="center", va="center", size=24, alpha=0.5)

axes_5 = plt.subplot(G[-1, -2])
plt.xticks([])
plt.yticks([])
plt.text(0.5, 0.5, "Axes 5", ha="center", va="center", size=24, alpha=0.5)
plt.suptitle('Subplot with gridspec')

plt.tight_layout()
../../_images/1f7e17ac043c410797341ad5fd8cc488ee06fa0bf2dbd05f2517ab22ec3a809c.png

Axes#

Axes are very similar to subplots but allow placement of plots at any location in the figure. So if we want to put a smaller plot inside a bigger one we do so with axes.

Hide code cell source

plt.axes((0.1, 0.1, 0.8, 0.8))
plt.xticks([])
plt.yticks([])
plt.text(
    0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5
);
../../_images/e7294c08f6ede253980275307c5d1d92adecd8a1da4bda4e5b8c5d137bd1a833.png

Hide code cell source

plt.axes((0.2, 0.2, 0.3, 0.3))
plt.xticks([])
plt.yticks([])
plt.text(
    0.5, 0.5, "axes([0.2, 0.2, 0.3, 0.3])", ha="center", va="center", size=16, alpha=0.5
);
../../_images/2ed141e6ef86c3c7b38b5aecfbfd483e6892b367d2e1006379fc3c06e2f132de.png

Ticks#

Well formatted ticks are an important part of publishing-ready figures. Matplotlib provides a totally configurable system for ticks. There are tick locators to specify where ticks should appear and tick formatters to give ticks the appearance you want. Major and minor ticks can be located and formatted independently from each other. Per default minor ticks are not shown, i.e. there is only an empty list for them because it is as NullLocator (see below).

Tick Locators#

Tick locators control the positions of the ticks. They are set as follows:

ax = plt.gca()
ax.xaxis.set_major_locator(eval(locator))

There are several locators for different kind of requirements:

Hide code cell source

from matplotlib import ticker

def tickline():
    plt.xlim(0, 10), plt.ylim(-1, 1), plt.yticks([])
    ax = plt.gca()
    ax.spines["right"].set_color("none")
    ax.spines["left"].set_color("none")
    ax.spines["top"].set_color("none")
    ax.xaxis.set_ticks_position("bottom")
    ax.spines["bottom"].set_position(("data", 0))
    ax.yaxis.set_ticks_position("none")
    ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
    ax.plot(np.arange(11), np.zeros(11))
    return ax

locators = [
    "ticker.NullLocator()",
    "ticker.MultipleLocator(1.0)",
    "ticker.FixedLocator([0, 2, 8, 9, 10])",
    "ticker.IndexLocator(3, 1)",
    "ticker.LinearLocator(5)",
    "ticker.LogLocator(2, [1.0])",
    "ticker.AutoLocator()",
]

n_locators = len(locators)

size = 512, 40 * n_locators
dpi = 72.0
figsize = size[0] / float(dpi), size[1] / float(dpi)
fig = plt.figure(figsize=figsize, dpi=dpi)
fig.patch.set_alpha(0)

for i, locator in enumerate(locators):
    plt.subplot(n_locators, 1, i + 1)
    ax = tickline()
    ax.xaxis.set_major_locator(eval(locator))
    plt.text(5, 0.3, locator[7:], ha="center")

plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99)
../../_images/34cb85df9f0ff26d96fb7117b0fc05035c2dc52f77eaa303a65ca54f7b3368f2.png

All of these “locators” (see code above) derive from the base class matplotlib.ticker.Locator. You can make your own locator deriving from it. Handling dates as ticks can be especially tricky. Therefore, matplotlib provides special locators in matplotlib.dates.

Other Types of Plots: examples and exercises#

Regular Plots#

Hide code cell source

n = 256
X = np.linspace(-np.pi, np.pi, n)
Y = np.sin(2 * X)

plt.axes((0.025, 0.025, 0.95, 0.95))

plt.plot(X, Y + 1, color="blue", alpha=1.00)
plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25)

plt.plot(X, Y - 1, color="blue", alpha=1.00)
plt.fill_between(X, -1, Y - 1, (Y - 1) > -1, color="blue", alpha=0.25)
plt.fill_between(X, -1, Y - 1, (Y - 1) < -1, color="red", alpha=0.25)

plt.xlim(-np.pi, np.pi)
plt.xticks([])
plt.ylim(-2.5, 2.5)
plt.yticks([]);
../../_images/bb7be40ed941789e2a9dddb44298e43d32d745f373e46cee9dd8fab13da645d7.png

Click on the hidden code for the figure above for solution.

Scatter Plots#

Hide code cell source

n = 1024
rng = np.random.default_rng()
X = rng.normal(0, 1, n)
Y = rng.normal(0, 1, n)
T = np.arctan2(Y, X)

plt.axes((0.025, 0.025, 0.95, 0.95))
plt.scatter(X, Y, s=75, c=T, alpha=0.5)

plt.xlim(-1.5, 1.5)
plt.xticks([])
plt.ylim(-1.5, 1.5)
plt.yticks([]);
../../_images/beea1449c3e438ac35bfc244728240eba3cc1a91473e1b8d2b8a1b8caebd41e2.png

Click on the hidden code for the figure above for solution.

Bar Plots#

Hide code cell source

n = 12
X = np.arange(n)
rng = np.random.default_rng()
Y1 = (1 - X / n) * rng.uniform(0.5, 1.0, n)
Y2 = (1 - X / n) * rng.uniform(0.5, 1.0, n)

plt.axes((0.025, 0.025, 0.95, 0.95))
plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")

for x, y in zip(X, Y1):
    plt.text(x, y + 0.05, f"{y:.2f}", ha="center", va="bottom")

for x, y in zip(X, Y2):
    plt.text(x, -y - 0.05, f"{y:.2f}", ha="center", va="top")

plt.xlim(-0.5, n)
plt.xticks([])
plt.ylim(-1.25, 1.25)
plt.yticks([]);
../../_images/afebd1dfb65981f19d2d1aa377624c63a4de661eb9e47b696bfeabc0638e57d0.png

Click on the hidden code for the figure above for solution.

Contour Plots#

Hide code cell source

def f(x, y):
    return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.axes((0.025, 0.025, 0.95, 0.95))

plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot")
C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5)
plt.clabel(C, inline=1, fontsize=10)

plt.xticks([])
plt.yticks([]);
../../_images/87a0c14c06c560cb208f2316524fc799b8491251ac889e9bc32b4ca406bace50.png

Click on the hidden code for the figure above for solution.

Imshow#

Hide code cell source

def f(x, y):
    return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2) - y**2)

n = 10
x = np.linspace(-3, 3, int(3.5 * n))
y = np.linspace(-3, 3, int(3.0 * n))
X, Y = np.meshgrid(x, y)
Z = f(X, Y)

plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower")
plt.axes((0.025, 0.025, 0.95, 0.95))
plt.colorbar(shrink=0.92)

plt.xticks([])
plt.yticks([]);
../../_images/402bfdc718a13763748ce27dfa9285fa6b903128fc88f634f429325daca8b6db.png

Click on the hidden code for the figure above for solution.

Pie Charts#

Hide code cell source

n = 20
Z = np.ones(n)
Z[-1] *= 2

plt.axes((0.025, 0.025, 0.95, 0.95))

plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)])
plt.axis("equal")
plt.xticks([])
plt.yticks();
../../_images/ad15289134fc34e013a81bf34bd4a5d538bf488d3ad69030749b6ee59ee7fc1b.png

Click on the hidden code for the figure above for solution.

Quiver Plots#

Hide code cell source

n = 8
X, Y = np.mgrid[0:n, 0:n]
T = np.arctan2(Y - n / 2.0, X - n / 2.0)
R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2)
U, V = R * np.cos(T), R * np.sin(T)

plt.axes((0.025, 0.025, 0.95, 0.95))
plt.quiver(X, Y, U, V, R, alpha=0.5)
plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5)

plt.xlim(-1, n)
plt.xticks([])
plt.ylim(-1, n)
plt.yticks([]);
../../_images/15e237ce8c20457b912f9d1221ab403a7e04a46aa017b7ed660bb0cb0f3f3e60.png

Click on the hidden code for the figure above for solution.

Grids#

Hide code cell source

from matplotlib import ticker

ax = plt.axes((0.025, 0.025, 0.95, 0.95))

ax.set_xlim(0, 4)
ax.set_ylim(0, 3)
ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0))
ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1))
ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75")
ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75")
ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75")
ax.grid(which="minor", axis="y", linewidth=0.25, linestyle="-", color="0.75")
ax.set_xticklabels([])
ax.set_yticklabels([]);
../../_images/ee27687fabf9c00c343e8e4dfe181c9d58346040f7706075fb9d200eced208a3.png

Click on the hidden code for the figure above for solution.

Multi Plots#

Hide code cell source

fig = plt.figure()
fig.subplots_adjust(bottom=0.025, left=0.025, top=0.975, right=0.975)

plt.subplot(2, 1, 1)
plt.xticks([]), plt.yticks([])

plt.subplot(2, 3, 4)
plt.xticks([])
plt.yticks([])

plt.subplot(2, 3, 5)
plt.xticks([])
plt.yticks([])

plt.subplot(2, 3, 6)
plt.xticks([])
plt.yticks([]);
../../_images/472b5daf1bb9ae1f7921082a8fdfb6e15adc2d1f0322937b90a41b6382fe6956.png

Click on the hidden code for the figure above for solution.

Polar Axis#

Hide code cell source

import matplotlib

jet = matplotlib.colormaps["jet"]

ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True)

N = 20
theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N)
rng = np.random.default_rng()
radii = 10 * rng.random(N)
width = np.pi / 4 * rng.random(N)
bars = plt.bar(theta, radii, width=width, bottom=0.0)

for r, bar in zip(radii, bars, strict=True):
    bar.set_facecolor(jet(r / 10.0))
    bar.set_alpha(0.5)

ax.set_xticklabels([])
ax.set_yticklabels([]);
../../_images/13fac49047465f64d01727b3890132181192baf0cad9eb0c1870841a84008d74.png

Click on the hidden code for the figure above for solution.

3D Plots#

Hide code cell source

from mpl_toolkits.mplot3d import Axes3D

ax: Axes3D = plt.figure().add_subplot(projection="3d")
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot")
ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot")
ax.set_zlim(-2, 2);
../../_images/12b3a3a9c7682cff15e33859aff34a5e9978a99a913c1b39025e7e5f1ea5ac44.png

Click on the hidden code for the figure above for solution.

Text#

Hide code cell source

eqs = []
eqs.append(
    r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$"
)
eqs.append(
    r"$\frac{d\rho}{d t} + \rho \vec{v}\cdot\nabla\vec{v} = -\nabla p + \mu\nabla^2 \vec{v} + \rho \vec{g}$"
)
eqs.append(r"$\int_{-\infty}^\infty e^{-x^2}dx=\sqrt{\pi}$")
eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$")
eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$")

plt.axes((0.025, 0.025, 0.95, 0.95))

rng = np.random.default_rng()

for i in range(24):
    index = rng.integers(0, len(eqs))
    eq = eqs[index]
    size = np.random.uniform(12, 32)
    x, y = np.random.uniform(0, 1, 2)
    alpha = np.random.uniform(0.25, 0.75)
    plt.text(
        x,
        y,
        eq,
        ha="center",
        va="center",
        color="#11557c",
        alpha=alpha,
        transform=plt.gca().transAxes,
        fontsize=size,
        clip_on=True,
    )
plt.xticks([])
plt.yticks([]);
../../_images/eaafaf2b25e935a590c6a9e51608d259f367196633d258d8f601108058700f69.png

Click on the hidden code for the figure above for solution.


Quick read

If you want to do a first quick pass through the Scientific Python Lectures to learn the ecosystem, you can directly skip to the next chapter: SciPy: high-level scientific computing.

The remainder of this chapter is not necessary to follow the rest of the intro part. But be sure to come back and finish this chapter later.

Beyond this tutorial#

Matplotlib benefits from extensive documentation as well as a large community of users and developers. Here are some links of interest:

Tutorials#

  • Pyplot tutorial

    • Introduction

    • Controlling line properties

    • Working with multiple figures and axes

    • Working with text

  • Image tutorial

    • Startup commands

    • Importing image data into NumPy arrays

    • Plotting NumPy arrays as images

  • Text tutorial

    • Text introduction

    • Basic text commands

    • Text properties and layout

    • Writing mathematical expressions

    • Text rendering With LaTeX

    • Annotating text

  • Artist tutorial

    • Introduction

    • Customizing your objects

    • Object containers

    • Figure container

    • Axes container

    • Axis containers

    • Tick containers

  • Path tutorial

    • Introduction

    • Bézier example

    • Compound paths

  • Transforms tutorial

    • Introduction

    • Data coordinates

    • Axes coordinates

    • Blended transformations

    • Using offset transforms to create a shadow effect

    • The transformation pipeline

Matplotlib documentation#

Code documentation#

The code is well documented and you can quickly access a specific command from within a python session:

import matplotlib.pyplot as plt
help(plt.plot)
Help on function plot in module matplotlib.pyplot:

plot(*args: 'float | ArrayLike | str', scalex: 'bool' = True, scaley: 'bool' = True, data=None, **kwargs) -> 'list[Line2D]'
    Plot y versus x as lines and/or markers.

    Call signatures::

        plot([x], y, [fmt], *, data=None, **kwargs)
        plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

    The coordinates of the points or line nodes are given by *x*, *y*.

    The optional parameter *fmt* is a convenient way for defining basic
    formatting like color, marker and linestyle. It's a shortcut string
    notation described in the *Notes* section below.

    >>> plot(x, y)        # plot x and y using default line style and color
    >>> plot(x, y, 'bo')  # plot x and y using blue circle markers
    >>> plot(y)           # plot y using x as index array 0..N-1
    >>> plot(y, 'r+')     # ditto, but with red plusses

    You can use `.Line2D` properties as keyword arguments for more
    control on the appearance. Line properties and *fmt* can be mixed.
    The following two calls yield identical results:

    >>> plot(x, y, 'go--', linewidth=2, markersize=12)
    >>> plot(x, y, color='green', marker='o', linestyle='dashed',
    ...      linewidth=2, markersize=12)

    When conflicting with *fmt*, keyword arguments take precedence.


    **Plotting labelled data**

    There's a convenient way for plotting objects with labelled data (i.e.
    data that can be accessed by index ``obj['y']``). Instead of giving
    the data in *x* and *y*, you can provide the object in the *data*
    parameter and just give the labels for *x* and *y*::

    >>> plot('xlabel', 'ylabel', data=obj)

    All indexable objects are supported. This could e.g. be a `dict`, a
    `pandas.DataFrame` or a structured numpy array.


    **Plotting multiple sets of data**

    There are various ways to plot multiple sets of data.

    - The most straight forward way is just to call `plot` multiple times.
      Example:

      >>> plot(x1, y1, 'bo')
      >>> plot(x2, y2, 'go')

    - If *x* and/or *y* are 2D arrays, a separate data set will be drawn
      for every column. If both *x* and *y* are 2D, they must have the
      same shape. If only one of them is 2D with shape (N, m) the other
      must have length N and will be used for every data set m.

      Example:

      >>> x = [1, 2, 3]
      >>> y = np.array([[1, 2], [3, 4], [5, 6]])
      >>> plot(x, y)

      is equivalent to:

      >>> for col in range(y.shape[1]):
      ...     plot(x, y[:, col])

    - The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*
      groups::

      >>> plot(x1, y1, 'g^', x2, y2, 'g-')

      In this case, any additional keyword argument applies to all
      datasets. Also, this syntax cannot be combined with the *data*
      parameter.

    By default, each line is assigned a different style specified by a
    'style cycle'. The *fmt* and line property parameters are only
    necessary if you want explicit deviations from these defaults.
    Alternatively, you can also change the style cycle using
    :rc:`axes.prop_cycle`.


    Parameters
    ----------
    x, y : array-like or float
        The horizontal / vertical coordinates of the data points.
        *x* values are optional and default to ``range(len(y))``.

        Commonly, these parameters are 1D arrays.

        They can also be scalars, or two-dimensional (in that case, the
        columns represent separate data sets).

        These arguments cannot be passed as keywords.

    fmt : str, optional
        A format string, e.g. 'ro' for red circles. See the *Notes*
        section for a full description of the format strings.

        Format strings are just an abbreviation for quickly setting
        basic line properties. All of these and more can also be
        controlled by keyword arguments.

        This argument cannot be passed as keyword.

    data : indexable object, optional
        An object with labelled data. If given, provide the label names to
        plot in *x* and *y*.

        .. note::
            Technically there's a slight ambiguity in calls where the
            second label is a valid *fmt*. ``plot('n', 'o', data=obj)``
            could be ``plt(x, y)`` or ``plt(y, fmt)``. In such cases,
            the former interpretation is chosen, but a warning is issued.
            You may suppress the warning by adding an empty format string
            ``plot('n', 'o', '', data=obj)``.

    Returns
    -------
    list of `.Line2D`
        A list of lines representing the plotted data.

    Other Parameters
    ----------------
    scalex, scaley : bool, default: True
        These parameters determine if the view limits are adapted to the
        data limits. The values are passed on to
        `~.axes.Axes.autoscale_view`.

    **kwargs : `~matplotlib.lines.Line2D` properties, optional
        *kwargs* are used to specify properties like a line label (for
        auto legends), linewidth, antialiasing, marker face color.
        Example::

        >>> plot([1, 2, 3], [1, 2, 3], 'go-', label='line 1', linewidth=2)
        >>> plot([1, 2, 3], [1, 4, 9], 'rs', label='line 2')

        If you specify multiple lines with one plot call, the kwargs apply
        to all those lines. In case the label object is iterable, each
        element is used as labels for each set of data.

        Here is a list of available `.Line2D` properties:

        Properties:
        agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image
        alpha: float or None
        animated: bool
        antialiased or aa: bool
        clip_box: `~matplotlib.transforms.BboxBase` or None
        clip_on: bool
        clip_path: Patch or (Path, Transform) or None
        color or c: :mpltype:`color`
        dash_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
        dash_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
        dashes: sequence of floats (on/off ink in points) or (None, None)
        data: (2, N) array or two 1D arrays
        drawstyle or ds: {'default', 'steps', 'steps-pre', 'steps-mid', 'steps-post'}, default: 'default'
        figure: `~matplotlib.figure.Figure` or `~matplotlib.figure.SubFigure`
        fillstyle: {'full', 'left', 'right', 'bottom', 'top', 'none'}
        gapcolor: :mpltype:`color` or None
        gid: str
        in_layout: bool
        label: object
        linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
        linewidth or lw: float
        marker: marker style string, `~.path.Path` or `~.markers.MarkerStyle`
        markeredgecolor or mec: :mpltype:`color`
        markeredgewidth or mew: float
        markerfacecolor or mfc: :mpltype:`color`
        markerfacecoloralt or mfcalt: :mpltype:`color`
        markersize or ms: float
        markevery: None or int or (int, int) or slice or list[int] or float or (float, float) or list[bool]
        mouseover: bool
        path_effects: list of `.AbstractPathEffect`
        picker: float or callable[[Artist, Event], tuple[bool, dict]]
        pickradius: float
        rasterized: bool
        sketch_params: (scale: float, length: float, randomness: float)
        snap: bool or None
        solid_capstyle: `.CapStyle` or {'butt', 'projecting', 'round'}
        solid_joinstyle: `.JoinStyle` or {'miter', 'round', 'bevel'}
        transform: unknown
        url: str
        visible: bool
        xdata: 1D array
        ydata: 1D array
        zorder: float

    See Also
    --------
    scatter : XY scatter plot with markers of varying size and/or color (
        sometimes also called bubble chart).

    Notes
    -----

    .. note::

        This is the :ref:`pyplot wrapper <pyplot_interface>` for `.axes.Axes.plot`.

    **Format Strings**

    A format string consists of a part for color, marker and line::

        fmt = '[marker][line][color]'

    Each of them is optional. If not provided, the value from the style
    cycle is used. Exception: If ``line`` is given, but no ``marker``,
    the data will be a line without markers.

    Other combinations such as ``[color][marker][line]`` are also
    supported, but note that their parsing may be ambiguous.

    **Markers**

    =============   ===============================
    character       description
    =============   ===============================
    ``'.'``         point marker
    ``','``         pixel marker
    ``'o'``         circle marker
    ``'v'``         triangle_down marker
    ``'^'``         triangle_up marker
    ``'<'``         triangle_left marker
    ``'>'``         triangle_right marker
    ``'1'``         tri_down marker
    ``'2'``         tri_up marker
    ``'3'``         tri_left marker
    ``'4'``         tri_right marker
    ``'8'``         octagon marker
    ``'s'``         square marker
    ``'p'``         pentagon marker
    ``'P'``         plus (filled) marker
    ``'*'``         star marker
    ``'h'``         hexagon1 marker
    ``'H'``         hexagon2 marker
    ``'+'``         plus marker
    ``'x'``         x marker
    ``'X'``         x (filled) marker
    ``'D'``         diamond marker
    ``'d'``         thin_diamond marker
    ``'|'``         vline marker
    ``'_'``         hline marker
    =============   ===============================

    **Line Styles**

    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style
    ``'--'``         dashed line style
    ``'-.'``         dash-dot line style
    ``':'``          dotted line style
    =============    ===============================

    Example format strings::

        'b'    # blue markers with default shape
        'or'   # red circles
        '-g'   # green solid line
        '--'   # dashed line with default color
        '^k:'  # black triangle_up markers connected by a dotted line

    **Colors**

    The supported color abbreviations are the single letter codes

    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue
    ``'g'``          green
    ``'r'``          red
    ``'c'``          cyan
    ``'m'``          magenta
    ``'y'``          yellow
    ``'k'``          black
    ``'w'``          white
    =============    ===============================

    and the ``'CN'`` colors that index into the default property cycle.

    If the color is the only part of the format string, you can
    additionally use any  `matplotlib.colors` spec, e.g. full names
    (``'green'``) or hex strings (``'#008000'``).

Galleries#

The matplotlib gallery is also incredibly useful when you search how to render a given graphic. Each example comes with its source.

Mailing lists#

Finally, there is a user mailing list where you can ask for help and a developers mailing list that is more technical.

Quick reference#

Here is a set of tables that show main properties and styles.

Line properties#

Property

Description

Appearance

alpha (or a)

alpha transparency on 0-1 scale

../../_images/20c89d4e9772ef97230a0ef096559dc9f4ba997dbb2bcec73345531879d519b3.png

anti-aliased

True or False - use anti-aliased rendering

../../_images/40b7e1488dfc10e46df5677798f269a5e929c36840bacde7cf71426b31da5b2f.png ../../_images/f817e154501310cf12f060318d301e3f12b4deacdad103a98d90dfb2e27a3cec.png

color (or c)

matplotlib color arg

../../_images/62e0e2fb94d3157fccd2f0e663403a04c25570c7bcad61ec7ba77aed32b62405.png

linestyle (or ls)

see Line properties

linewidth (or lw)

float, the line width in points

../../_images/3ba83f739cd1b94568fb01827f105b02b05b5fdf2f69a666c2b2bd56086e44e1.png

solid_capstyle

Cap style for solid lines

../../_images/3a10aaeca18e78811b7582786916f4541f16f40027b63803ecc45f4612e347af.png

solid_joinstyle

Join style for solid lines

../../_images/baee53b4a10dfa9d3fe3ecc67ad834d9fa591ac9d9faa20cfd4890a77e3eda54.png

dash_capstyle

Cap style for dashes

../../_images/3a10aaeca18e78811b7582786916f4541f16f40027b63803ecc45f4612e347af.png

dash_joinstyle

Join style for dashes

../../_images/c5cc2d6f5e7f79ae1d9109106813db588ccaf5db5281aa0d5b7aa900431ef6af.png

marker

see Markers

markeredgewidth (mew)

line width around the marker symbol

../../_images/292f4c939b3e6b85e1dfa8abcc28a889663271e4fcadedd397eb0e7179483494.png

markeredgecolor (mec)

edge color if a marker is used

../../_images/3e75ceb67cd4d7ccd2a2e53b7c457600753c8ba436f13c93158f5b18dbf0e220.png

markerfacecolor (mfc)

face color if a marker is used

../../_images/7fb5146f213cd3245debe8cf6b6b43d8caec3696dd2fba91bd38f60302ce1eb7.png

markersize (ms)

size of the marker in points

../../_images/2c2eb449be8462f89100e3e670acb13dda249890fc73e9c39e1b48fa3d899bd8.png

See the Line property figures for code to generate graphics for the table above.

Line styles#

../../_images/3026b2173a12efff432dc528be308e134a145f143538654f05bf4c20dd84bd11.png

See Line style figure for code.

Markers#

../../_images/a06834b0b93d1fbf752c402c425608c75b5ee62babf33c8b7f6961fda741f734.png

See Marker style figure for code.

Colormaps#

All colormaps can be reversed by appending _r. For instance, gray_r is the reverse of gray.

If you want to know more about colormaps, check the documentation on Colormaps in matplotlib.

../../_images/1bfca9a241e12f5ee1a97e78e15fcae61dbac01660a71a468801a4ca3d54f1e0.png

See Colormap figure for code.