Để tự động vẽ dữ liệu lên lưới subplots (3 hàng x 2 cột) bằng vòng lặp và hàm:
Các bước
- Thiết lập figure size và autolayout.
- Tạo figure và mảng axes 3x2 bằng plt.subplots(3, 2).
- Định nghĩa hàm iterate_columns(cols, x) để vẽ dữ liệu x lên từng cột.
- Duyệt qua từng hàng axes, tạo dữ liệu ngẫu nhiên và gọi hàm vẽ cột.
- Hiển thị bằng show().
Ví dụ
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axes = plt.subplots(3, 2)
def iterate_columns(cols, x):
for col in cols:
col.plot(x, color='red')
for row in axes:
x = np.random.normal(0, 1, 100).cumsum()
iterate_columns(row, x)
plt.show()
Kết quả
