Matplotlib subplot chia figure thành lưới, vẽ nhiều biểu đồ độc lập trong một hình.
Cài đặt
pip install matplotlib
Ví dụ: 2 subplot dọc (damped oscillation)
import numpy as np
import matplotlib.pyplot as plt
x1 = np.linspace(0.0, 6.0)
x2 = np.linspace(0.0, 3.0)
y1 = np.cos(2.3 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2.4 * np.pi * x2)
plt.subplot(2, 1, 1) # 2 hàng, 1 cột, vị trí 1
plt.plot(x1, y1, 'o-')
plt.title('2 biểu đồ dùng "subplot"')
plt.ylabel('Plot 1')
plt.subplot(2, 1, 2) # vị trí 2
plt.plot(x2, y2, '.-')
plt.xlabel('x-axis')
plt.ylabel('Plot 2')
plt.show()
Kết quả

Giải thích
subplot(nrows, ncols, index)index bắt đầu từ 1, duyệt hàng trước.- Mỗi subplot có trục, tiêu đề, nhãn riêng.
- Phù hợp so sánh 2 dataset liên quan.
Phương pháp OOP: fig, axes = plt.subplots(2, 1) → axes[0].plot(...), axes[1].plot(...) linh hoạt hơn.