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

วิธีวาดเส้น/ลูกศรนอกพื้นที่ Axes ใน Matplotlib

การวาดเส้นหรือลูกศรที่ล้นออกนอกพื้นที่ Axes (Data Area) ใน Matplotlib สามารถทำได้โดยใช้ annotate() พร้อมระบุ xycoords และ xytext ในระบบพิกัดที่ต่างกัน

หลักการ

  • xycoords='axes fraction': พิกัดสัมพัทธ์กับ Axes (0,0 = มุมซ้ายล่าง, 1,1 = มุมขวาบน)
  • xytext: ตำแหน่งปลายลูกศร/ข้อความ
  • arrowprops: กำหนดรูปแบบลูกศร

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

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()

# ข้อมูลตัวอย่าง
x = np.linspace(-2, 2, 100)
y = np.sin(x * 2)
ax.plot(x, y, 'b-', linewidth=2)

# 1. ลูกศรแนวนอนข้ามทั้งกราฟ (ด้านล่าง Axes)
ax.annotate('', 
            xy=(0, -0.15), xycoords='axes fraction',  # เริ่ม: ซ้ายล่างนอก Axes
            xytext=(1, -0.15),                         # สิ้นสุด: ขวาล่างนอก Axes
            arrowprops=dict(arrowstyle='<->', color='blue', lw=2),
            annotation_clip=False)  # สำคัญ: อนุญาตให้วาดนอก Axes

# 2. ลูกศรแนวตั้งด้านขวา
ax.annotate('', 
            xy=(1.05, 0), xycoords='axes fraction',   # เริ่ม: ขวา กลาง
            xytext=(1.05, 1),                          # สิ้นสุด: ขวา บน
            arrowprops=dict(arrowstyle='<->', color='green', lw=2),
            annotation_clip=False)

# 3. ลูกศรชี้จากข้อมูลไปข้อความนอก Axes
ax.annotate('Peak Value', 
            xy=(0.5, 1), xycoords='data',             # จุดบนกราฟ (Data Coords)
            xytext=(1.15, 0.8), textcoords='axes fraction',  # ข้อความนอก Axes
            arrowprops=dict(arrowstyle='->', color='red', lw=1.5,
                            connectionstyle='arc3,rad=0.2'),
            fontsize=11, fontweight='bold',
            annotation_clip=False)

# 4. เส้นแนวนอนข้าม Figure (ใช้ Figure Coordinates)
from matplotlib.patches import ConnectionPatch
# ต้องใช้ Figure Coordinates สำหรับข้าม Axes
con = ConnectionPatch(xyA=(0, 0.5), coordsA=ax.transAxes,
                      xyB=(1, 0.5), coordsB=ax.transAxes,
                      arrowstyle='<->', color='purple', lw=1.5)
fig.add_artist(con)

ax.set_xlim(-2.5, 2.5)
ax.set_ylim(-1.5, 1.5)
ax.set_title('Drawing Lines/Arrows Outside Axes Area', fontsize=14)
ax.grid(True, alpha=0.3)

plt.show()

ผลลัพธ์

กราฟพร้อมลูกศรและเส้นที่ล้นออกนอกพื้นที่ Plot Area (Axes) อยู่ในพื้นที่ Figure

พารามิเตอร์สำคัญของ arrowprops

พารามิเตอร์คำอธิบายตัวอย่าง
arrowstyleรูปแบบลูกศร'->', '<->', '-[', 'fancy', 'simple', 'wedge'
color / ecสีลูกศร'red', '#FF0000', (1,0,0)
lw / linewidthความหนาเส้น1.5, 2, 3
connectionstyleรูปแบบเส้นเชื่อม'arc3,rad=0.2', 'angle3,angleA=0,angleB=90'
shrinkA, shrinkBย่อทิ้งปลาย (Points)5, 10
mutation_scaleขนาดหัวลูกศร10, 15, 20

ระบบพิกัด (Coordinate Systems)

  • 'data': พิกัดข้อมูล (Default)
  • 'axes fraction': 0-1 สัมพัทธ์กับ Axes
  • 'figure fraction': 0-1 สัมพัทธ์กับ Figure ทั้งหมด
  • 'offset points': จุด Offset จาก xy
  • annotation_clip=False: สำคัญมาก - อนุญาตให้วาดนอก Axes