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

Đặt văn bản ở góc hình vẽ equal aspect trong Matplotlib

Để đặt chú thích (annotation) ở góc của hình vẽ có tỷ lệ khung hình bằng nhau (equal aspect), dùng annotate() với xycoords='axes fraction'.

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo figure và 2 subplots dọc bằng subplots(2).
  • Tạo dữ liệu x và vẽ trên 2 axes.
  • Duyệt các axes, dùng annotate() với xy=(1,0), xycoords='axes fraction', alignment right/bottom.
  • Hiển thị bằng show().

Ví dụ

from matplotlib import pyplot as plt
import numpy as np

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

fig, axes = plt.subplots(2)
x = np.linspace(-2, 2, 10)
axes[0].plot(x)
axes[1].plot(x, 2*x)
for ax in axes:
    ax.annotate('Straight Line', xy=(1, 0), xycoords='axes fraction', fontsize=10, horizontalalignment='right', verticalalignment='bottom')
plt.show()

Kết quả

Đặt văn bản ở góc hình vẽ equal aspect trong Matplotlib