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

Thiết lập lề (margins) cho figure Matplotlib

Để đặt lề (margins) xung quanh dữ liệu trong axes, dùng plt.margins(x=0, y=0) (0 = không có lề phụ).

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu t, y.
  • Tạo 2 subplot ngang: 121 (không margins), 122 (có margins).
  • Vẽ cùng dữ liệu trên cả 2.
  • Trên subplot 2: plt.margins(x=0, y=0).
  • Hiển thị bằng show().

Ví dụ

import numpy as np
from matplotlib import pyplot as plt

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

t = np.linspace(-2, 2, 10)
y = np.exp(-t)
plt.subplot(121)
plt.plot(t, y)
plt.title("Without margins")
plt.subplot(122)
plt.plot(t, y)
plt.title("With x=0 and y=0 margins")
plt.margins(x=0, y=0)
plt.show()

Kết quả

Thiết lập lề (margins) cho figure Matplotlib