Để annotate (ghi chú) các điểm từ Pandas DataFrame trong Matplotlib:
- Thiết lập kích thước figure và padding
- Tạo DataFrame 2D với cột
x, y, textc - Vẽ cột
x,ybằngplot() - Ghép nối đối tượng Pandas theo trục
- Lặp qua đối tượng Pandas
- Đặt text cho mỗi điểm bằng
text() - Hiển thị bằng
show()
Ví dụ mã nguồn
import pandas as pd
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
df = pd.DataFrame(dict(x=[2, 4, 1, 5, 2], y=[2, 1, 3, 5, 7], text=['First', 'Second', 'Third', 'Fourth', 'Fifth']))
ax = df.set_index('x')['y'].plot(style='*', color='red', ms=20)
a = pd.concat({'x': df.x, 'y': df.y, 'text': df.text}, axis=1)
for i, point in a.iterrows():
ax.text(point['x']+0.125, point['y'], str(point['text']))
plt.show()
Kết quả
Scatter plot dấu * đỏ, mỗi điểm có text annotation bên phải: First, Second, Third, Fourth, Fifth.

Cách hiện đại hơn: Dùng ax.annotate() hoặc list comprehension: [ax.text(x, y, t) for x, y, t in zip(df.x, df.y, df.text)].