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

การใช้ขนาดฟอนต์หลายขนาดใน Label เดียวของ Matplotlib

Matplotlib ไม่รองรับการตั้งค่า Font Size หลายขนาดใน String เดียวโดยตรง แต่สามารถทำได้ด้วย Mathtext (LaTeX-like syntax) หรือใช้ TextArea + HPacker จาก matplotlib.offsetbox

วิธีที่ 1: ใช้ Mathtext (ง่ายที่สุด)

ใช้ Syntax แบบ LaTeX ภายใน String: $\\bf{Text}$, $\\large{Text}$, $\\small{Text}$

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x, y, 'b-', linewidth=2)

# ใช้ Mathtext สำหรับ Font Size หลายขนาด
# \large, \Large, \LARGE, \huge, \Huge / \small, \footnotesize, \scriptsize, \tiny
title_text = (r"$\large{\bf{Main Title:}}$ $\normalsize{y = \cos(x)}$ "
              r"$\small{\textit{(Sample Data)}}$ $\tiny{[Units: Arbitrary]}$")

ax.set_title(title_text, fontsize=14, pad=20)
ax.set_xlabel(r"$\large{X}$ $\small{(radians)}$", fontsize=12)
ax.set_ylabel(r"$\large{Y}$ $\small{(amplitude)}$", fontsize=12)

ax.grid(True, alpha=0.3)
plt.show()

วิธีที่ 2: ใช้ OffsetBox (ควบคุมได้ละเอียดกว่า)

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import TextArea, HPacker, VPacker, AnchoredOffsetbox

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

x = np.linspace(-5, 5, 100)
y = np.cos(x)

fig, ax = plt.subplots()
ax.plot(x, y, 'b-', linewidth=2)

# สร้าง TextArea แต่ละส่วนด้วย Font Size ต่างกัน
main_title = TextArea("Main Title: ", textprops=dict(fontsize=16, fontweight='bold', color='navy'))
equation = TextArea("y = cos(x)", textprops=dict(fontsize=14, fontstyle='italic', color='darkred'))
subtitle = TextArea(" (Sample Data)", textprops=dict(fontsize=10, color='gray'))
units = TextArea(" [Units: Arbitrary]", textprops=dict(fontsize=8, color='lightgray'))

# รวมแนวนอน
hp = HPacker(children=[main_title, equation, subtitle, units], align='center', pad=2, sep=2)

# วางบน Axes
anchored = AnchoredOffsetbox(loc='upper center', child=hp, pad=0.3, frameon=False,
                             bbox_to_anchor=(0.5, 1.02), bbox_transform=ax.transAxes)
ax.add_artist(anchored)

ax.set_xlabel("X (radians)", fontsize=12)
ax.set_ylabel("Y (amplitude)", fontsize=12)
ax.grid(True, alpha=0.3)

plt.show()

วิธีที่ 3: ใช้ Annotate หลายตัว (Manual Positioning)

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [10, 6]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()
x = np.linspace(-5, 5, 100)
ax.plot(x, np.cos(x), 'b-', linewidth=2)

# วางข้อความหลายตำแหน่งด้วย Font Size ต่างกัน
ax.text(0.5, 1.05, "Main Title:", transform=ax.transAxes, 
        fontsize=16, fontweight='bold', ha='center', color='navy')
ax.text(0.5, 1.00, "y = cos(x)", transform=ax.transAxes, 
        fontsize=14, fontstyle='italic', ha='center', color='darkred')
ax.text(0.5, 0.95, "(Sample Data)", transform=ax.transAxes, 
        fontsize=10, ha='center', color='gray')
ax.text(0.5, 0.91, "[Units: Arbitrary]", transform=ax.transAxes, 
        fontsize=8, ha='center', color='lightgray')

ax.set_xlabel("X (radians)", fontsize=12)
ax.set_ylabel("Y (amplitude)", fontsize=12)
ax.grid(True, alpha=0.3)

plt.show()

ผลลัพธ์

Title/Label แสดงข้อความหลายส่วนที่มี Font Size, Style, และ Color ต่างกันในบรรทัดเดียว

สรุป Mathtext Font Size Commands

CommandRelative Size
\tiny50%
\scriptsize70%
\footnotesize80%
\small90%
\normalsize100% (Base)
\large120%
\Large144%
\LARGE173%
\huge207%
\Huge249%

คำแนะนำ

  • Mathtext ใช้ได้กับ title(), xlabel(), ylabel(), text(), annotate(), legend()
  • ใช้ Raw String r"..." เพื่อหลีกเลี่ยง Escape Character
  • สำหรับ Layout ซับซ้อน ใช้ offsetbox (วิธีที่ 2)
  • เปิดใช้งาน LaTeX จริงด้วย plt.rcParams['text.usetex'] = True (ต้องติดตั้ง LaTeX)