Multiple plots side by side

4.5. Multiple plots side by side#

In some situations, it is useful to show multiple plots side by side in a same figure. This can be done using the plt.subplot function, which splits a figure into a grid and specifies the location of the next plot on this grid. Its arguments are:

  1. The number of lines (int);

  2. The number of columns (int);

  3. The location of the next plot, starting at 1 in the upper left corner, then going left to right then up to down:

_images/9ee2660fdff00fb0041c9bfe370645321443ed4b7822f6a80201cd49f5b94905.png

For instance, to spread five plots on two lines and three columns:

import matplotlib.pyplot as plt

y1 = [1.0, 2.0, 3.0, 1.0]
y2 = [1.0, 3.0, -1.0, 2.0]
y3 = [-1.0, 4.0, -2.0, 2.0]
y4 = [-1.0, -4.0, -3.0, 0.0]
y5 = [2.0, 3.0, -1.0, 1.0]

plt.subplot(2, 3, 1)
plt.plot(y1)
plt.title("First plot")

plt.subplot(2, 3, 2)
plt.plot(y2)
plt.title("Second plot")

plt.subplot(2, 3, 3)
plt.plot(y3)
plt.title("Third plot")

plt.subplot(2, 3, 4)
plt.plot(y4)
plt.title("Fourth plot")

plt.subplot(2, 3, 5)
plt.plot(y5)
plt.title("Fifth plot");
_images/67609d5c0e1c5038b6ae4a389067c86d953048745715cd97dfc2e8a6b5d93764.png

We can see that the titles of the second line overlaps with the horizontal axes of the first line. This is a common issue with Matplotlib: it does not know how to optimize the spacing while we progressively build the figure. Calling plt.tight_layout just after building the figure optimizes the spacing so that everything looks clean.

plt.subplot(2, 3, 1)
plt.plot(y1)
plt.title("First plot")

plt.subplot(2, 3, 2)
plt.plot(y2)
plt.title("Second plot")

plt.subplot(2, 3, 3)
plt.plot(y3)
plt.title("Third plot")

plt.subplot(2, 3, 4)
plt.plot(y4)
plt.title("Fourth plot")

plt.subplot(2, 3, 5)
plt.plot(y5)
plt.title("Fifth plot")

plt.tight_layout()
_images/30be508c63dda054a96a6ef98e0271674d9b9bf76c9a2e57a013db903d7b3ccd.png