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

Cách viết annotation ngoài vùng vẽ theo tọa độ dữ liệu trong Matplotlib

Ta có thể dùng annotate() để đặt chú thích bên ngoài vùng vẽ.

Các bước thực hiện

  • Thiết lập kích thước hình và khoảng đệm.
  • Tạo dữ liệu x, y bằng NumPy.
  • Tạo hình và subplots bằng subplots().
  • Vẽ scatter với marker sao, colormap copper.
  • Đặt annotation ngoài bằng tọa độ xy phù hợp.
  • 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

x = np.random.rand(100)
y = np.random.rand(100)

fig, ax = plt.subplots()
ax.scatter(x, y, c=y, marker="*", cmap="copper")

ax.annotate('Scatter points (outside the drawing)', xy=(0.30, 1.05), xycoords=ax.get_xaxis_transform())
plt.show()

Kết quả

Cách viết annotation ngoài vùng vẽ theo tọa độ dữ liệu trong Matplotlib