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

Python Matplotlib - วาดวงกลมพร้อม Annotation บนกราฟ

ใช้ Matplotlib วาดจุดข้อมูล วาดวงกลมรอบจุดที่สนใจ และเพิ่ม Annotation พร้อมลูกศร

ขั้นตอน

  1. ตั้งค่า Figure
  2. สร้างข้อมูลและเลือกจุดที่จะทำเครื่องหมาย
  3. Plot ข้อมูลทั้งหมด
  4. ตั้งค่า Axis Limits
  5. วาดวงกลม: plot(x, y, 'o', ms=radius*2, mec='yellow', mfc='none', mew=2)
  6. เพิ่ม Annotation: annotate() พร้อม arrowprops

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

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

data = np.array([[5, 3, 4, 4, 6],
                 [1, 5, 3, 2, 2]])

point = data[:, 2]  # จุดที่ 3 (Index 2)
ax = plt.gca()

ax.plot(data[0], data[1], 'o', ms=10, color='red')
ax.set_xlim([2, 8])
ax.set_ylim([0, 6])

radius = 15
ax.plot(point[0], point[1], 'o',
        ms=radius * 2, mec='yellow', mfc='none', mew=2)

ax.annotate('Circled Marker', xy=point, xytext=(60, 60),
            textcoords='offset points',
            color='green', size='large',
            arrowprops=dict(
                arrowstyle='simple,tail_width=0.3,head_width=0.8,head_length=0.8',
                facecolor='b', shrinkB=radius * 1.2)
            )

plt.show()

คำอธิบาย

  • ms = Marker Size, mec = Marker Edge Color, mfc = Marker Face Color, mew = Marker Edge Width
  • mfc='none' ทำให้วงกลมโปร่งใส (Hollow Circle)
  • annotate() เพิ่มข้อความพร้อมลูกศร arrowprops ปรับสไตล์ลูกศรได้
  • shrinkB ย่อลูกศรให้ไม่ทับ Marker