การใช้ LaTeX Preamble กำหนดเองใน Matplotlib
Matplotlib รองรับการตั้งค่า LaTeX preamble ผ่าน rcParams เพื่อปรับแต่งการแสดงผลสูตรคณิตศาสตร์
ขั้นตอนหลัก
- ตั้งค่าขนาดรูปและ padding
- สร้างข้อมูล x และ y แบบสุ่มด้วย numpy
- พล็อตข้อมูลด้วย plot() ใช้ LaTeX formatting ใน label เช่น label="$y=e^{x}$"
- วางตำนานด้วย legend()
- แสดงผลด้วย show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-10, 10, 100)
y = np.exp(x)
plt.plot(x, y, color='red', label="$y=e^{x}$")
plt.legend(loc='upper right')
plt.show()
คำอธิบาย
label ใช้ LaTeX syntax ภายใน $...$ สำหรับ inline math mode
หมายเหตุ
สำหรับ preamble ที่ซับซ้อน ตั้งค่า plt.rcParams['text.latex.preamble'] = r'\usepackage{...}'