Introduction to matplotlib#

Matplotlib is a comprehensive library for creating static and animated visualizations 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

Visualizing Arrays with Matplotlib#

Let’s create an array to visualize 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/6c16a6f2637dfb4f96853c90e9b73c317aa42457bc5d46c13a26e3b2fec1af0a.png

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

plt.pcolormesh(xx);
_images/48ca3aa98966c2069e1aa100938f36ecbf0df2d8675c03726aa7b5dca936d9d6.png
f = np.sin(xx) * np.cos(0.5 * yy)
plt.pcolormesh(f)
<matplotlib.collections.QuadMesh at 0x7f6978716f90>
_images/80b9fff0cb274566b8e3d3590907d18a28d5d970ab43332a743070cc0f847b15.png
g = f * x
plt.pcolormesh(g)
<matplotlib.collections.QuadMesh at 0x7f6978312250>
_images/b46593f18e4cbb445af2aa985f6e7fdc065b5608a909e80250315da28b6ce24c.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 0x7f697870fb10>]
_images/38e0066018458310c212b110727f176594005fa0ad08c416a93586e857e724c8.png
plt.plot(g_xmean, y)
[<matplotlib.lines.Line2D at 0x7f697820c250>]
_images/ffd3dc4b62cd3506bd30586dd070efe44d7d2d6c9b96215cd75c7af26a501be7.png

Figures and Axes#

The figure is the highest level of organization 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/8bca872709ac2b0f25d92a4a17e6f88f8c26e62fd976798443d98310b3ed3224.png

Subplots#

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

fig, ax = plt.subplots()
_images/9e13561b06f5d2c575e2e9d0ab28f3ca3efd7ae4d5738c0cd619a55149090489.png
ax
<Axes: >
fig, axes = plt.subplots(ncols=2, figsize=(8, 4), subplot_kw={"facecolor": "blue"})
_images/851b990779cdb6eee326ec4afebe14ab1ece59045c52c3d2c1608ab3212c47dd.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 0x7f6978310190>]
_images/db3db9ea422842a926d9652d0f9b87c5e5aad225c18841732ba5e57d8f0b9ea9.png

This does the same thing as

plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f697822bf50>]
_images/db3db9ea422842a926d9652d0f9b87c5e5aad225c18841732ba5e57d8f0b9ea9.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 0x7f6978190a90>]
_images/2cb5896f279d2448236869e762009e2589d50fce3e582edead65912555fe2d44.png

Labeling Plots#

Labeling 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/c95be4a9e39e7cfb7a6fb9eaf58a0a004e48319ae116ae0fae7ff389498b394d.png

Customizing Plots#

fig, ax = plt.subplots()
ax.plot(x, y, x, z)
[<matplotlib.lines.Line2D at 0x7f69782bb6d0>,
 <matplotlib.lines.Line2D at 0x7f696ff0f990>]
_images/7157c9ecb9ed95a8840266ff53bf42160b891b6f9337af0b92a1c2baa6e0408a.png

It’s simple to switch axes

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

Line Styles#

fig, ax = plt.subplots()
ax.plot(x, y, linestyle="--")
ax.plot(x, z, linestyle=":")
[<matplotlib.lines.Line2D at 0x7f696c95ecd0>]
_images/9ab503c6bc7c9c162bdad176920b81c9d7d0b1122b6e24dc8dfb97d62d2821b4.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 0x7f696c9aee50>]
_images/d0eb2738066ea7eb22a228ec12ee986cfa1ed7cd337fb352b98eb1129a6458b8.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 0x7f696c9d4090>]
_images/0073d511e649d6d5d5acca463e0a00cafcfadbbe5fdb1b84c463ddffb1660102.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/cbb644a6b0b81247e30707498f13866996d5ce9ca968f64043b9c8bb503443ca.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 0x7f696c8a7ed0>
_images/a0b3276f7cd85b4a5d00bea154c34b640e49d49dcba9036909a169003f32141a.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/34e1aae86c9b847901c1d8e7e273b75eda77417e22e3ec6199ddad2d977f1d33.png