การใส่สัญลักษณ์องศา (°) ใน Matplotlib ทำได้โดยใช้รูปแบบ LaTeX ภายในสตริงข้อความ โดยใช้ $^\circ$ หรือ \textdegree ร่วมกับ raw string (r"")
ขั้นตอนการทำงาน
- นำเข้า
numpyและmatplotlib.pyplot - สร้างข้อมูลตัวอย่าง (Pressure-Volume, Temperature)
- พลอตกราฟด้วย
plt.plot() - ตั้งค่าแกน X ด้วย
plt.xlabel() - ตั้งค่าแกน Y พร้อมสัญลักษณ์องศา:
plt.ylabel("Temperature ($^\circ$C)") - แสดงผลด้วย
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
pV = np.array([3, 5, 1, 7, 10, 9, 4, 2])
nR = np.array([31, 15, 11, 51, 12, 71, 41, 13])
T = np.divide(pV, nR)
plt.plot(pV, T, c="red")
plt.xlabel("Pressure x Volume")
plt.ylabel("Temperature ($^\circ$C)")
plt.show()
วิธีใส่สัญลักษณ์พิเศษต่างๆ ใน Matplotlib
| สัญลักษณ์ | LaTeX Code | ตัวอย่าง |
|---|---|---|
| องศา (°) | $^\circ$ หรือ \degree | r"$25^\circ$C" |
| ไมโคร (µ) | \mu | r"$\mu$m" |
| อัลฟา (α) | \alpha | r"$\alpha$" |
| เบต้า (β) | \beta | r"$\beta$" |
| พาย (π) | \pi | r"$\pi$" |
| ซิกมา (Σ) | \Sigma | r"$\Sigma x_i$" |
| อนันต์ (∞) | \infty | r"$\infty$" |
| ยกกำลัง | ^2 | r"$x^2$" |
| ดัชนีล่าง | _1 | r"$x_1$" |
การใช้ Raw String (แนะนำ)
# ใช้ r"" เพื่อป้องกัน escape sequence
plt.title(r"Temperature: $25^\circ$C")
plt.xlabel(r"Wavelength ($\mu$m)")
plt.ylabel(r"$\alpha$-particle flux")
# รวมกับ f-string (Python 3.6+)
temp = 25
plt.title(rf"Temperature: ${temp}^\circ$C")
การเปิดใช้งาน LaTeX จริง (usetex=True)
plt.rcParams['text.usetex'] = True
plt.title(r"Temperature: $25^\circ$C") # ใช้ LaTeX engine จริง
# ต้องมี LaTeX ติดตั้งในระบบ
การประยุกต์ใช้
จำเป็นสำหรับการนำเสนอข้อมูลทางวิทยาศาสตร์ วิศวกรรม ฟิสิกส์ เคมี ที่ต้องใช้หน่วยและสัญลักษณ์มาตรฐานสากล (SI units)