Để chọn và thao tác trên một subplot cụ thể trong lưới subplots, ta dùng add_subplot() với chỉ số vị trí.
Các bước
- Thiết lập figure size và autolayout.
- Tạo figure mới bằng plt.figure().
- Duyệt qua các chỉ số subplot (1, 2, 3, 4) và thêm axes bằng add_subplot(1, 4, index).
- Vẽ dữ liệu ngẫu nhiên trên mỗi axes.
- Chọn lại subplot thứ 2 (index=2) và vẽ đường màu đỏ đè lên.
- 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 = plt.figure()
for index in [1, 2, 3, 4]:
ax = fig.add_subplot(1, 4, index)
ax.plot(np.random.rand(5), np.random.rand(5))
ax = fig.add_subplot(1, 4, 2)
ax.plot(np.random.rand(5), np.random.rand(5), color='red')
plt.show()
Kết quả
