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

วิธีใส่สัญลักษณ์องศา (Degree Symbol) ในกราฟ Python Matplotlib

การใส่สัญลักษณ์องศา (°) ใน Matplotlib ทำได้โดยใช้รูปแบบ LaTeX ภายในสตริงข้อความ โดยใช้ $^\circ$ หรือ \textdegree ร่วมกับ raw string (r"")

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

  1. นำเข้า numpy และ matplotlib.pyplot
  2. สร้างข้อมูลตัวอย่าง (Pressure-Volume, Temperature)
  3. พลอตกราฟด้วย plt.plot()
  4. ตั้งค่าแกน X ด้วย plt.xlabel()
  5. ตั้งค่าแกน Y พร้อมสัญลักษณ์องศา: plt.ylabel("Temperature ($^\circ$C)")
  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

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$ หรือ \degreer"$25^\circ$C"
ไมโคร (µ)\mur"$\mu$m"
อัลฟา (α)\alphar"$\alpha$"
เบต้า (β)\betar"$\beta$"
พาย (π)\pir"$\pi$"
ซิกมา (Σ)\Sigmar"$\Sigma x_i$"
อนันต์ (∞)\inftyr"$\infty$"
ยกกำลัง^2r"$x^2$"
ดัชนีล่าง_1r"$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)