Introduction to matplotlib#

Matplotlib is a comprehensive library for creating static and animated visualisations in Python.

Note

Documentation for this package is available at https://matplotlib.org/stable/index.html.

Note

If you have not yet set up Python on your computer, you can execute this tutorial in your browser via Google Colab. Click on the rocket in the top right corner and launch “Colab”. If that doesn’t work download the .ipynb file and import it in Google Colab

Then, install numpy and matplotlib by executing the following command in a Jupyter cell at the top of the notebook. We will use numpy to create some of the data that we will visualize with matplotlib.

!pip install matplotlib numpy

Importing a Package#

Besides numpy, we import the module pyplot from the matplotlib library and nicknames it as plt for brevity in the code.

import numpy as np
from matplotlib import pyplot as plt

Visualising Arrays with Matplotlib#

Let’s create an array to visualise it.

x = np.linspace(-2 * np.pi, 2 * np.pi, 100)
y = np.linspace(-np.pi, np.pi, 50)
xx, yy = np.meshgrid(x, y)
xx.shape, yy.shape
((50, 100), (50, 100))

For plotting a 1D array as a line, we use the plot command.

plt.plot(x);
_images/0415c19d89b6fb54b005fcd6b79a40c927eae92d594350855517ab15cd07120f.png

There are many ways to visualise 2D data. He we use pcolormesh.

plt.pcolormesh(xx);
_images/0f82649206c05ad56a1422cb9844c812988d78a284f8081a35f51f4f7f98c785.png
f = np.sin(xx) * np.cos(0.5 * yy)
plt.pcolormesh(f)
<matplotlib.collections.QuadMesh at 0x10d6a1950>
_images/d9e18b8526a9659a626fb5ca26c0ee0d831d460467cc9ef5338779646ec22824.png
g = f * x
plt.pcolormesh(g)
<matplotlib.collections.QuadMesh at 0x10d701a90>
_images/ad2fd730ddec07c0cbf87124734a7bc614d57d970702b3197b3fcdfaec903485.png
# apply on just one axis
g_ymean = g.mean(axis=0)
g_xmean = g.mean(axis=1)
plt.plot(x, g_ymean)
[<matplotlib.lines.Line2D at 0x10d771a90>]
_images/65078594d8db9ca2541ff3a409005c6b79633faaaf4a2242f042976e375891e0.png
plt.plot(g_xmean, y)
[<matplotlib.lines.Line2D at 0x10d7c7890>]
_images/6dce9f3aa45a574450bfe1e5b56f24ee40cadc601ac60aad5716f1c2ab43fbb7.png

Figures and Axes#

The figure is the highest level of organisation of matplotlib objects.

fig = plt.figure()
<Figure size 640x480 with 0 Axes>
fig = plt.figure(figsize=(13, 5))
<Figure size 1300x500 with 0 Axes>
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
_images/d38543d90ef1fb71876e3313618808cf2ef74fd8ac2697a970ebede2291d58ba.png

Subplots#

Subplot syntax is a more convenient way to specify the creation of multiple axes.

fig, ax = plt.subplots()
_images/f61f5e1894116d0d4bdde7dcdc31d687adf144526ad5ab32c36137e3afca57fd.png
ax
<Axes: >
fig, axes = plt.subplots(ncols=2, figsize=(8, 4), subplot_kw={"facecolor": "blue"})
_images/4045d0013f256e65f25f476606e082695127b7147c463ecae5b6d3d504e60e2d.png
axes
array([<Axes: >, <Axes: >], dtype=object)

Drawing into Axes#

All plots are drawn into axes.

# create some data to plot
import numpy as np

x = np.linspace(-np.pi, np.pi, 100)
y = np.cos(x)
z = np.sin(6 * x)
fig, ax = plt.subplots()
ax.plot(x, y)
[<matplotlib.lines.Line2D at 0x10d91c550>]
_images/7e0de3bdac87a5e0fb68347cc542d2c7370666c7a0250b9ccd8ccad96da0c426.png

This does the same thing as

plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x10d990190>]
_images/7e0de3bdac87a5e0fb68347cc542d2c7370666c7a0250b9ccd8ccad96da0c426.png

This starts to matter when we have multiple axes to manage.

fig, axes = plt.subplots(figsize=(8, 4), ncols=2)
ax0, ax1 = axes
ax0.plot(x, y)
ax1.plot(x, z)
[<matplotlib.lines.Line2D at 0x10d80aad0>]
_images/2abe891d3238f86741b88c2be29113422344f2463ef25023eef5e27c4822b98d.png

Labelling Plots#

Labelling plots is very important! We want to know what data is shown and what the units are. matplotlib offers some functions to label graphics.

fig, ax = plt.subplots(figsize=(4, 4))

ax.plot(x, y)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_title("x vs. y")

# squeeze everything in
plt.tight_layout()
_images/d77fbea0e7efe08d74048e34b7b145097abc834cc1a9b1e3e38f53365004f92a.png

Customising Plots#

fig, ax = plt.subplots()
ax.plot(x, y, x, z)
[<matplotlib.lines.Line2D at 0x10daef4d0>,
 <matplotlib.lines.Line2D at 0x10daef610>]
_images/d873ff56c68060e3383b9bad71477cc46b777e338db1d79a50c15628047ea214.png

It’s simple to switch axes

fig, ax = plt.subplots()
ax.plot(y, x, z, x)
[<matplotlib.lines.Line2D at 0x10db83250>,
 <matplotlib.lines.Line2D at 0x10db83390>]
_images/dab2f57e09130619496eabc049a0953cf35e9ed5f38ae6980e1b9e6b5e2ae3cb.png

Line Styles#

fig, ax = plt.subplots()
ax.plot(x, y, linestyle="--")
ax.plot(x, z, linestyle=":")
[<matplotlib.lines.Line2D at 0x10dc0b110>]
_images/ce6197f1022c58d229f6c1aaeb117a7cb46e78b2e672be4bcb66b6bf42eb6895.png

Colors#

As described in the colors documentation, there are some special codes for commonly used colors.

fig, ax = plt.subplots()
ax.plot(x, y, color="black")
ax.plot(x, z, color="red")
[<matplotlib.lines.Line2D at 0x10e84b250>]
_images/0ac6ac51bf8f7636318fe9fbd520044b2d06e2074eb1ee4dc24ce08e91166318.png

Markers#

There are lots of different markers availabile in matplotlib!

fig, ax = plt.subplots()
ax.plot(x[:20], y[:20], marker="o", markerfacecolor="red", markeredgecolor="black")
ax.plot(x[:20], z[:20], marker="^", markersize=10)
[<matplotlib.lines.Line2D at 0x10e87f110>]
_images/ec41cffd3b8b01e7a35b276d8efbb2bb85d577e82115fb2706b1098702a6f038.png

Axis Limits#

fig, ax = plt.subplots()
ax.plot(x, y, x, z)
ax.set_xlim(-5, 5)
ax.set_ylim(-3, 3)
(-3.0, 3.0)
_images/d66af41841f71923f257885be85688f5c41087a02d7278de7dc946928a938ece.png

Scatter Plots#

fig, ax = plt.subplots()

splot = ax.scatter(y, z, c=x, s=(100 * z**2 + 5), cmap="viridis")
fig.colorbar(splot)
<matplotlib.colorbar.Colorbar at 0x10d48f4d0>
_images/52fa26586cc4c88f6df7c0101ea97b1afccba0e78e986cb2ec06c78a53bfd02b.png

There are many different colormaps available in matplotlib: https://matplotlib.org/stable/tutorials/colors/colormaps.html

Bar Plots#

labels = ["Bhadla", "Noor"]
values = [2225, 1177]

fig, ax = plt.subplots(figsize=(5, 5))
ax.bar(labels, values)

ax.set_ylabel("MW")

plt.tight_layout()
_images/dde1af00ff744dec882ac6d943248262dcd6223baebefcffa7bbb42026f72f4b.png