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

ตั้งค่าฟอนต์ Bold สำหรับ LaTeX Axes Label ใน Matplotlib


ภาพรวม

สาธิตการตั้งค่า Axes Labels ให้เป็น Bold โดยใช้ LaTeX Markup $\bf{...}$ ใน Matplotlib

ขั้นตอน

  1. สร้างข้อมูล X, Y ด้วย NumPy
  2. สร้าง Subplot และตั้งค่า Ticks
  3. พลอตข้อมูล
  4. ตั้งค่า Tick Labels ด้วย $\bf{...}$ สำหรับ Bold
  5. ตั้งค่า Font Family (ตัวอย่าง: Comic Sans MS)
  6. ปรับ Layout และแสดงผล

ตัวอย่างโค้ด

import numpy as np
from matplotlib import pyplot as plt, font_manager as fm

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
plt.rcParams["font.fantasy"] = "Comic Sans MS"

x = np.array([1, 2, 3, 4])
y = np.exp(x)

ax1 = plt.subplot()
ax1.set_xticks(x)
ax1.set_yticks(y)
ax1.plot(x, y, c="red")

ax1.set_xticklabels(["$\bf{one}$", "$\bf{two}$", "$\bf{three}$", "$\bf{four}$"], rotation=45)
ax1.set_yticklabels(["$\bf{:.2f}$".format(y[0]), "$\bf{:.2f}$".format(y[1]),
                     "$\bf{:.2f}$".format(y[2]), "$\bf{:.2f}$".format(y[3])], rotation=45)

plt.tight_layout()
plt.show()

ผลลัพธ์

Tick Labels แสดงเป็นตัวหนา (Bold) หมุน 45 องศา ใช้ฟอนต์ Comic Sans MS

หมายเหตุ

  • $\bf{...}$ ทำงานกับ MathText built-in ไม่ต้องติดตั้ง LaTeX
  • สำหรับ Axes Labels (xlabel, ylabel) ใช้ plt.xlabel(r'$\bf{Label}$')