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/79c1bed38abe45e8f45d74d7229e961fa365b0562f81eec53af68d15d99d17c6.png

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

plt.pcolormesh(xx);
_images/60c8cb1ff0577d3922c76216739ca9a2c71a062e6de60167ce7ab4ae52ae14c7.png
f = np.sin(xx) * np.cos(0.5 * yy)
plt.pcolormesh(f)
<matplotlib.collections.QuadMesh at 0x7f41ac95f4d0>
_images/3269b32d66c8199d746ca2385ddd90b6afa5c1fe4ab1517aea0ce7a227bb0bd2.png
g = f * x
plt.pcolormesh(g)
<matplotlib.collections.QuadMesh at 0x7f41ac9a4650>
_images/56d2df0840cae2c45b30e2b076ac5d8d68938ce4ec840dfa20d627b40a8f5046.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 0x7f41ac962150>]
_images/17b4ec6f2da74d2a7c9a80f88d8168bc89350b5a364dd2ef2bbea7195f9d7d9d.png
plt.plot(g_xmean, y)
[<matplotlib.lines.Line2D at 0x7f41ac712f50>]
_images/9893e792d991dec05d48b9737a8f7ae79b350534655f3a07035c8bca863a28d6.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/08023fd932938f6c2522a1e7286e5ac1399db4f4d5c02e3f329156d2f62a365f.png

Subplots#

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

fig, ax = plt.subplots()
_images/0cbf1359a7a70fab4cc16a8c1e9c6fe1bc989234a4665de6aff9e1106c6b267b.png
ax
<Axes: >
fig, axes = plt.subplots(ncols=2, figsize=(8, 4), subplot_kw={"facecolor": "blue"})
_images/64ff485f08c52c876d37b3f9ad812b7bc00ec54e4d12f565971390a06318f42e.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 0x7f41ac3a1c10>]
_images/f6946a1e7455b910864ed47c0381fca37e4e550c92acaeb1cfdd867950fd5bbd.png

This does the same thing as

plt.plot(x, y)
[<matplotlib.lines.Line2D at 0x7f41ac2048d0>]
_images/f6946a1e7455b910864ed47c0381fca37e4e550c92acaeb1cfdd867950fd5bbd.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 0x7f41ac3f7610>]
_images/b0a8a2a1659eb2d244523342fe03275ed5894a6ccbf64425bfb4da9d3cf3f111.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/14812189ce92a1c8a1b7a2872c42ae3feb3fd88534472f02413f74a3721d8941.png

Customizing Plots#

fig, ax = plt.subplots()
ax.plot(x, y, x, z)
[<matplotlib.lines.Line2D at 0x7f41ac288250>,
 <matplotlib.lines.Line2D at 0x7f41ac999110>]
_images/4e04790599035cb15de57953a68d2ae7a8f6da7bba905711c72a8dca5dedbe66.png

It’s simple to switch axes

fig, ax = plt.subplots()
ax.plot(y, x, z, x)
[<matplotlib.lines.Line2D at 0x7f41ac1f4f50>,
 <matplotlib.lines.Line2D at 0x7f41ac996310>]
_images/382e88abd641c14cf3b10d2be3056a471d71502b628056af820a2beaa283cf62.png

Line Styles#

fig, ax = plt.subplots()
ax.plot(x, y, linestyle="--")
ax.plot(x, z, linestyle=":")
[<matplotlib.lines.Line2D at 0x7f41ac194f90>]
_images/9b0f8e872d7171f1ff9611e53bc7508bb0efc645f13663b1b6514a03c97c48f8.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 0x7f41a3501f10>]
_images/6d70945c8652b17f2a9788f6d0873b6ab14b49e6816e7e3f87c23b2f133214f4.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 0x7f41a3582010>]
_images/ea6346fa3a7819120fadc51085d28604223ef1594da26fa37832552afbf5a971.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/acba6c0ba298401d457d5fc5195742c3956b449c341ea7460f116352f17eef6c.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 0x7f41a1f52590>
_images/6ccece6c291e20f1e70657ca068efb47b5e398fa09ac926d17d73e9ff7dc6e74.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/9f52c6800731b6fd3a4665091d95c3190a4abaeb845ede65a68dbef4b83449ff.png