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

Thêm chú thích in đậm (bold) trong Matplotlib

Để thêm văn bản chú thích in đậm, sử dụng cú pháp LaTeX $\\bf{text}$ trong phương thức annotate().

Các bước

  • Thiết lập figure size và autolayout.
  • Tạo dữ liệu xpoints, ypoints.
  • Tạo danh sách nhãn định dạng chuỗi.
  • Vẽ scatter plot.
  • Duyệt (label, x, y), gọi annotate(f"$\\bf{label}$", ...) với mũi tên.
  • 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

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ả

Thêm chú thích in đậm (bold) trong Matplotlib