Matplotlib Subplot
The subplot() function arranges multiple plots in a grid within a single figure by specifying the number of rows, columns, and a 1-indexed position for each plot.
Why Put Several Plots Together?
When you want to compare two or more datasets side by side, such as sales in two regions or the before-and-after of a calculation, drawing separate figures makes comparison harder. Matplotlib lets you place several plots inside one figure using a grid layout, so a reader can look at everything at once without switching between windows.
The subplot() Function
plt.subplot(nrows, ncols, index) tells Matplotlib to treat the current figure as a grid with nrows rows and ncols columns, and to draw the next plot into the cell given by index. The index counts positions left to right, then top to bottom, and — unlike almost everything else in Python — it starts at 1, not 0. The three arguments can be written with or without commas, so plt.subplot(1, 2, 1) and plt.subplot(121) mean the same thing.
Example
import matplotlib.pyplot as plt
import numpy as np
hours = np.array([1, 2, 3, 4, 5])
typing_speed = np.array([20, 28, 35, 41, 44])
reading_speed = np.array([80, 95, 110, 118, 125])
plt.subplot(1, 2, 1)
plt.plot(hours, typing_speed)
plt.title("Typing speed")
plt.subplot(1, 2, 2)
plt.plot(hours, reading_speed)
plt.title("Reading speed")
plt.suptitle("Practice progress over 5 days")
plt.show()Example
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1, 10)
plt.subplot(2, 3, 1)
plt.plot(x, x)
plt.title("Linear")
plt.subplot(2, 3, 2)
plt.plot(x, x ** 2)
plt.title("Squared")
plt.subplot(2, 3, 3)
plt.plot(x, x ** 3)
plt.title("Cubed")
plt.subplot(2, 3, 4)
plt.plot(x, np.sqrt(x))
plt.title("Square root")
plt.subplot(2, 3, 5)
plt.plot(x, np.log(x))
plt.title("Log")
plt.subplot(2, 3, 6)
plt.plot(x, np.sin(x))
plt.title("Sine")
plt.tight_layout()
plt.show()- nrows * ncols must be at least as large as the highest index you use — a 2x2 grid only has slots 1 through 4.
- Every plt.subplot() call in the same figure should use the same nrows and ncols, otherwise Matplotlib redraws the whole grid and your earlier plots can be resized or discarded.
- Index counts across a row first, then moves to the next row, always starting from 1 in the top-left cell.
- Call plt.tight_layout() after the last subplot to stop titles and labels from overlapping neighboring plots.
Titling One Plot vs. the Whole Figure
plt.title() labels only the subplot that is currently active — the one from the most recent plt.subplot() call. To label the entire figure, use plt.suptitle(), which places one heading above the whole grid.