Để thêm văn bản chú thích trong Matplotlib cho nhiều điểm, chúng ta có thể thực hiện các bước sau:
- Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
- Tạo điểm dữ liệu x và y bằng numpy.
- Để đặt nhãn cho mỗi điểm phân tán, tạo danh sách nhãn.
- Vẽ xpoints, ypoints bằng phương thức scatter(). Về màu, dùng xpoints.
- Lặp qua zip của nhãn, xpoints và ypoints.
- Dùng phương thức annotate() với biểu diễn LaTeX bold trong vòng lặp for.
- Để hiển thị figure, dùng phương thức 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
xpoints = np.linspace(1, 10, 10)
ypoints = np.random.rand(10)
labels = ["%.2f" % i for i in xpoints]
plt.scatter(xpoints, ypoints, c=xpoints)
for label, x, y in zip(labels, xpoints, ypoints):
plt.annotate(
f"$\\bf{label}$", xy=(x, y), xytext=(-20, 20), textcoords='offset points',
ha='center', va='bottom', arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'))
plt.show()
Kết quả

