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/59f37f71746a2f034d66257691efddeacbe2c60c4e72043581349e45b72c17dd.png

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

plt.pcolormesh(xx);
_images/b735547287136418f6877bb19716e101e7886f81366e1ea5f2766f490013c340.png
f = np.sin(xx) * np.cos(0.5 * yy)
plt.pcolormesh(f)
<matplotlib.collections.QuadMesh at 0x7f7b5dc42c50>
_images/9a9c28f60d761ff2969689d770ace939066e805219cf1f548bd20a8d9a6c8231.png
g = f * x
plt.pcolormesh(g)
<matplotlib.collections.QuadMesh at 0x7f7b5ff98490>
_images/ae7cdc8c06b520ea3522a36dfbe962ab8532c062d1003a7ff891de8a530fead6.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 0x7f7b5ffdb450>]
_images/9a153da544f113ca7467ca1f4ab1195f8686681a71ad9f6c52b295f7ed001d55.png
plt.plot(g_xmean, y)
[<matplotlib.lines.Line2D at 0x7f7b5dd5cc50>]
_images/1fded03b32e495737d509594c246a8f0c01bf79f19ad849acc95b266f4c9ff57.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/08ecbafa3ab09bac3c2447803d9c77aa09f63d1658cf685672f85371574751df.png

Subplots#

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

fig, ax = plt.subplots()
_images/45816d171484af6f5b3de210bb3ae3d5c2ef9ecbcb6905647d8f0d99ce65e1a7.png
ax
<Axes: >
fig, axes = plt.subplots(ncols=2, figsize=(8, 4), subplot_kw={"facecolor": "blue"})
_images/d13d7bcd4027f26608a4fa5b18749d5fb3b1bf1f7c2a5168a329fc7a8568e170.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 0x7f7b5db68d90>]
_images/26123995c5a7e6fd324c4795873fb9408c4c05a2bfad9a6250e928685fabf7fe.png

This does the same thing as

plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f7b5d7c4c50>]
_images/26123995c5a7e6fd324c4795873fb9408c4c05a2bfad9a6250e928685fabf7fe.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 0x7f7b5c5a37d0>]
_images/1f3d81c63cbac35e97b0a4646fb98dc43d1edd925b37da64ea7e97348b7a5894.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/013412ef4aec4968b9c53f539730f0c74d14b971781abd3f96f69b37e16b82bd.png

Customizing Plots#

fig, ax = plt.subplots()
ax.plot(x, y, x, z)
[<matplotlib.lines.Line2D at 0x7f7b5dd554d0>,
 <matplotlib.lines.Line2D at 0x7f7b5c5dea10>]
_images/53daff352457e204d31551780d6a2be0feeb84cf3ad3b32b2395e0a7169251e6.png

It’s simple to switch axes

fig, ax = plt.subplots()
ax.plot(y, x, z, x)
[<matplotlib.lines.Line2D at 0x7f7b5dc1f610>,
 <matplotlib.lines.Line2D at 0x7f7b5c467b50>]
_images/5d373d037cc35549347ed7313c4eaf2de195894c6be2724c8241c1540865740a.png

Line Styles#

fig, ax = plt.subplots()
ax.plot(x, y, linestyle="--")
ax.plot(x, z, linestyle=":")
[<matplotlib.lines.Line2D at 0x7f7b5c4d8d90>]
_images/8f149f7e2a01b1a9d45325bb7d841beaa0acc52bab96c365213e4a94df3196dd.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 0x7f7b5c382b50>]
_images/fcf4117463dd9ddbbcabd403cc9440556ed34076aa818bb415c9c749f9805648.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 0x7f7b5c3fed90>]
_images/0ce16396bb75dff3356909be408359cd19cab1833a8d72006aa8a91dc6d3522a.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/184c83bd6283960b8346bfc92a84c4030d3b2276f3187013bfbbd8bac11b495f.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 0x7f7b689e0490>
_images/f367543495bcb4b2143627f1249b6f0c8cba1135ea5b1abe2ebb3c7382f32637.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/46b6aeb140ca470f6664effcdd2568d259d37de26a5ac896fa1316133cc18af6.png