Matplotlib Subplot
Often you want several related charts side by side: the same measure for different groups, or different measures over the same time span. Subplots divide one figure into a grid of separate Axes.
plt.subplot(rows, cols, index)
plt.subplot() creates one Axes in a grid and makes it current. The index starts at 1 and counts left to right, top to bottom:
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 100)
plt.subplot(1, 2, 1) # 1 row, 2 columns, first plot
plt.plot(x, np.sin(x))
plt.title("sin")
plt.subplot(1, 2, 2) # 1 row, 2 columns, second plot
plt.plot(x, np.cos(x), color="C1")
plt.title("cos")
plt.show()
print("Axes in the figure:", len(plt.gcf().axes))Axes in the figure: 2
You can also write the three numbers as one: plt.subplot(122) is the same as plt.subplot(1, 2, 2) (only for grids smaller than 10×10).
A 2×2 grid
python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(1, 11)
plt.figure(figsize=(8, 6))
for i, (power, color) in enumerate([(1, "C0"), (2, "C1"), (0.5, "C2"), (-1, "C3")], start=1):
plt.subplot(2, 2, i)
plt.plot(x, x ** float(power), color=color, marker=".")
plt.title(f"$y = x^{{{power}}}quot;)
plt.suptitle("Four power functions")
plt.tight_layout()
plt.show()
print([ax.get_title() for ax in plt.gcf().axes])['$y = x^{1}