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

วิธีวางข้อความนอกพื้นที่กราฟใน Python Matplotlib

การวางข้อความนอกพื้นที่พลอต (Outside plot area) ใน Matplotlib สามารถทำได้โดยใช้ plt.text() พร้อม transform=plt.gcf().transFigure เพื่อใช้พิกัด Figure (0-1) แทนพิกัดข้อมูล

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

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูล X และ Y
  3. กำหนดตำแหน่งข้อความในพิกัด Figure: text_pos_x = 0.60, text_pos_y = 0.50
  4. พลอตกราฟด้วย plt.plot()
  5. เพิ่มข้อความด้วย plt.text() พร้อม:
    • transform=plt.gcf().transFigure - ใช้พิกัด Figure
    • fontsize, color ตามต้องการ
  6. แสดงผลด้วย plt.show()

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

import numpy as np
from matplotlib import pyplot as plt

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

x = np.linspace(1, 5, 100)
y = np.exp(x)
text_pos_x = 0.60
text_pos_y = 0.50

plt.plot(x, y, c='red')
plt.text(text_pos_x, text_pos_y, "$\mathit{y}=e^{x}$", fontsize=14,
         transform=plt.gcf().transFigure, color='green')
plt.show()

ระบบพิกัด Transform สำคัญ

Transformพิกัดใช้เมื่อ
ax.transDataData coordinatesวางข้อความตามค่าข้อมูล (ค่าเริ่มต้น)
ax.transAxesAxes coordinates (0-1)วางข้อความในพื้นที่ Axes
fig.transFigureFigure coordinates (0-1)วางข้อความนอก Axes / ทับ Figure

ตัวอย่างการใช้งานต่างๆ


# 1. ในพื้นที่ข้อมูล (Data coordinates)
ax.text(2, 50, "Data coords", transform=ax.transData)

# 2. ในพื้นที่ Axes (0-1 relative to axes)
ax.text(0.05, 0.95, "Axes coords", transform=ax.transAxes,
        va='top', ha='left')

# 3. นอก Figure (0-1 relative to figure)
fig.text(0.5, 0.02, "Figure coords - centered bottom", ha='center',
         transform=fig.transFigure)

# 4. ใช้ fig.text() โดยตรง (สะดวกกว่า plt.text + transFigure)
fig.text(0.95, 0.5, "Right side", rotation=90, va='center',
         transform=fig.transFigure)

การประยุกต์ใช้

เหมาะสำหรับ: Watermark, Copyright notice, Figure caption นอกพื้นที่กราฟ, Annotation ที่ต้องอยู่ตำแหน่งคงที่เทียบกับหน้ากระดาษ, Multi-panel figure labels (a), (b), (c)