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

Vẽ viền (border) cho subplots trong Matplotlib

Để vẽ viền bao quanh subplot, ta sử dụng patch Rectangle trên axes của subplot.

Các bước

  • Thiết lập figure size và autolayout.
  • Thêm subplot đầu tiên bằng subplot(121).
  • Lấy giới hạn trục của subplot.
  • Tạo hình chữ nhật Rectangle dựa trên giới hạn trục, thêm padding.
  • Thêm patch vào subplot bằng add_patch().
  • Tắt clipping để viền hiển thị ngoài vùng axes.
  • Thêm subplot thứ hai subplot(122) để so sánh.
  • Hiển thị bằng show().

Ví dụ

from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

sub = plt.subplot(121)
ax = sub.axis()
rec = plt.Rectangle((ax[0] - 0.7, ax[2] - 0.2), (ax[1] - ax[0]) + 1, (ax[3] - ax[2]) + 0.4, fill=False, lw=2, linestyle="dotted")
rec = sub.add_patch(rec)
rec.set_clip_on(False)
plt.title("with border")
sub = plt.subplot(122)
plt.title("without border")
plt.show()

Kết quả

Vẽ viền (border) cho subplots trong Matplotlib