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:
The number of lines (int);
The number of columns (int);
The location of the next plot, starting at 1 in the upper left corner, then going left to right then up to down:
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");
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()