การเปลี่ยน Font Name (Font Family) ของข้อความใน Legend Matplotlib สามารถทำได้หลายวิธี: ผ่าน rcParams (Global), พารามิเตอร์ legend(), หรือปรับ Text Object โดยตรงหลังสร้าง Legend
วิธีที่ 1: ใช้ rcParams (Global - ส่งผลทุก Legend)
import matplotlib.pyplot as plt import numpy as np # ตั้งค่า Global Font plt.rcParams['font.family'] = 'serif' # หรือ 'sans-serif', 'monospace', 'cursive', 'fantasy' plt.rcParams['font.serif'] = ['Times New Roman', 'DejaVu Serif'] # Fallback Fonts plt.rcParams['font.size'] = 12 # สำหรับ Legend เฉพาะ plt.rcParams['legend.fontsize'] = 11 plt.rcParams['legend.fontfamily'] = 'monospace' # Matplotlib 3.6+ x = np.linspace(0, 10, 50) plt.plot(x, np.sin(x), label='Sine') plt.plot(x, np.cos(x), label='Cosine') plt.legend() plt.show()
วิธีที่ 2: ระบุใน legend() โดยตรง (Per-Legend)
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), 'b-', label='Sine Wave')
ax.plot(x, np.cos(x), 'r--', label='Cosine Wave')
# ระบุ Font ใน legend()
legend = ax.legend(
fontsize=12,
fontfamily='monospace', # Font Family
fontweight='bold', # Bold
fontstyle='italic', # Italic
title='Functions',
title_fontsize=13,
title_fontweight='bold',
title_fontfamily='serif'
)
plt.show()
วิธีที่ 3: ปรับ Text Objects หลังสร้าง Legend (ยืดหยุ่นสุด)
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 10, 50)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), 'b-', label='Sine Wave (sin)')
ax.plot(x, np.cos(x), 'r--', label='Cosine Wave (cos)')
ax.plot(x, np.sin(x)*0.5, 'g:', label='Half Amplitude')
# สร้าง Legend ก่อน
legend = ax.legend(loc='upper right', fontsize=12)
# ปรับ Font ของแต่ละ Text ใน Legend
for i, text in enumerate(legend.get_texts()):
if i == 0:
text.set_fontfamily('serif')
text.set_fontsize(14)
text.set_color('blue')
text.set_fontweight('bold')
elif i == 1:
text.set_fontfamily('monospace')
text.set_fontsize(12)
text.set_color('red')
text.set_fontstyle('italic')
else:
text.set_fontfamily('sans-serif')
text.set_fontsize(10)
text.set_color('green')
# ปรับ Title ของ Legend
if legend.get_title():
legend.get_title().set_fontfamily('fantasy')
legend.get_title().set_fontsize(14)
legend.get_title().set_color('purple')
ax.set_title('Per-Item Legend Font Customization', fontsize=14)
plt.show()
ผลลัพธ์
Legend แสดงรายการแต่ละรายการด้วย Font Family, Size, Color, Style ที่ต่างกันตามที่กำหนด
ฟอนต์ที่มีในระบบ (System Fonts)
import matplotlib.font_manager as fm
# ดูฟอนต์ที่ติดตั้งอยู่
fonts = sorted([f.name for f in fm.fontManager.ttflist])
for f in fonts:
print(f)
# หรือหาเฉพาะที่รองรับภาษาไทย
thai_fonts = [f.name for f in fm.fontManager.ttflist if 'thai' in f.name.lower() or 'sarabun' in f.name.lower() or 'noto' in f.name.lower()]
print("Thai fonts:", thai_fonts)
คำแนะนำสำหรับภาษาไทย
- ใช้ฟอนต์ที่รองรับไทย: Sarabun, Noto Sans Thai, TH Sarabun New, Prompt, Kanit, Bai Jamjuree
- ตั้งค่า:
plt.rcParams['font.family'] = 'Sarabun'(ต้องติดตั้งในระบบ) - หรือ Embed Font:
fm.FontProperties(fname='/path/to/font.ttf')
สรุป Font Properties
| Property | ค่าตัวอย่าง | คำอธิบาย |
|---|---|---|
fontfamily / family | 'serif', 'sans-serif', 'monospace', 'Sarabun', 'Times New Roman' | Font Family |
fontsize / size | 10, 12, 14, 'large', 'x-large' | ขนาดฟอนต์ |
fontweight / weight | 'normal', 'bold', 'light', 'heavy', 100-900 | ความหนา |
fontstyle / style | 'normal', 'italic', 'oblique' | สไตล์ |
color | 'red', '#FF0000', (1,0,0) | สีข้อความ |