Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเขียน Annotation นอกพื้นที่วาดในพิกัดข้อมูล Matplotlib

ใช้ ax.annotate() พร้อม xycoords=ax.get_xaxis_transform() ซึ่งใช้พิกัด x แบบข้อมูล (data) แต่ y แบบ axes fraction (0-1) ทำให้วางข้อความนอกพื้นที่พลอตได้

ขั้นตอนการทำงาน

  1. ตั้งค่าขนาดรูปและเลย์เอาต์
  2. สร้างข้อมูล scatter แบบสุ่ม
  3. สร้าง figure และ axes
  4. พลอต scatter ด้วย ax.scatter()
  5. เพิ่ม annotation นอกพื้นที่ด้วย xy=(0.30, 1.05), xycoords=ax.get_xaxis_transform()
  6. แสดงผล

ตัวอย่างโค้ด

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()

ผลลัพธ์

การเขียน Annotation นอกพื้นที่วาดในพิกัดข้อมูล Matplotlib