Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo nhiều biểu đồ (subplots) lặp lại với Matplotlib trong Python

Matplotlib cho phép tạo nhiều subplot trong một figure bằng add_subplot hoặc subplots.

Cài đặt

pip install matplotlib

Ví dụ: 2 subplot chồng nhau (sine wave + histogram)


import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
fig.subplots_adjust(top=0.8)

# Subplot 1: sine wave
ax1 = fig.add_subplot(211)
ax1.set_ylabel('Y-axis')
ax1.set_title('Đồ thị sin')
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
ax1.plot(t, s, color='blue', lw=2)

# Subplot 2: histogram random
np.random.seed(4567232)
ax2 = fig.add_axes([0.15, 0.1, 0.7, 0.3])  # [left, bottom, width, height]
n, bins, patches = ax2.hist(np.random.randn(1000), 50,
                            facecolor='yellow', edgecolor='green')
ax2.set_xlabel('x-label')

plt.show()

Kết quả

Tạo nhiều biểu đồ (subplots) lặp lại với Matplotlib trong Python

Giải thích

  • add_subplot(211): lưới 2 hàng 1 cột, vị trí 1.
  • add_axes([left,bottom,width,height]): vị trí tuyệt đối trong figure (0-1).
  • subplots_adjust điều chỉnh khoảng cách.

Phương pháp hiện đại: Dùng fig, axes = plt.subplots(2, 1) để tạo mảng axes dễ quản lý.