ใช้ ax.annotate() พร้อม xycoords=ax.get_xaxis_transform() ซึ่งใช้พิกัด x แบบข้อมูล (data) แต่ y แบบ axes fraction (0-1) ทำให้วางข้อความนอกพื้นที่พลอตได้
ขั้นตอนการทำงาน
- ตั้งค่าขนาดรูปและเลย์เอาต์
- สร้างข้อมูล scatter แบบสุ่ม
- สร้าง figure และ axes
- พลอต scatter ด้วย
ax.scatter() - เพิ่ม annotation นอกพื้นที่ด้วย
xy=(0.30, 1.05), xycoords=ax.get_xaxis_transform() - แสดงผล
ตัวอย่างโค้ด
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()
ผลลัพธ์
