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

Thay đổi kích thước/vị trí subplot sau khi tạo axes trong Matplotlib

Dùng GridSpec để điều chỉnh vị trí subplot sau khi tạo.

  • Tạo figure, ax = add_subplot(111).
  • gs = gridspec.GridSpec(3, 1).
  • ax.set_position(gs[0:2].get_position(fig)).
  • ax.set_subplotspec(gs[0:2]).
  • fig.add_subplot(gs[2]) thêm subplot thứ 2 ở hàng 3.
  • tight_layout, show().

Ví dụ

from matplotlib import pyplot as plt
from matplotlib import gridspec as gridspec
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
gs = gridspec.GridSpec(3, 1)
ax.set_position(gs[0:2].get_position(fig))
ax.set_subplotspec(gs[0:2])
fig.add_subplot(gs[2])
fig.tight_layout()
plt.show()

Kết quả

Figure với subplot đầu chiếm 2/3 chiều cao, subplot thứ 2 chiếm 1/3 dưới cùng.