การกำหนดค่าและป้ายกำกับ (ticks และ tick labels) บนแกน Y เองใน Matplotlib ใช้ฟังก์ชัน plt.yticks() หรือ ax.set_yticks() และ ax.set_yticklabels()
ขั้นตอนการทำงาน
- นำเข้า
numpyและmatplotlib.pyplot - สร้างข้อมูล X และ Y ด้วย
np.array() - สร้างรายการป้ายกำกับที่ต้องการ (เช่น
['a', 'b', 'c', 'd']) - ตั้งค่า ticks และ labels บนแกน X และ Y ด้วย
plt.xticks()และplt.yticks() - พลอตกราฟด้วย
plt.plot() - ปรับขอบเขตด้วย
plt.margins(x=0, y=0) - แสดงผลด้วย
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
x = np.array([0, 2, 4, 6])
y = np.array([1, 3, 5, 7])
ticks = ['a', 'b', 'c', 'd']
plt.xticks(x, ticks)
plt.yticks(y, ticks)
plt.plot(x, y, c='green')
plt.margins(x=0, y=0)
plt.show()
วิธีใช้ Object-Oriented API (แนะนำ)
fig, ax = plt.subplots()
ax.set_xticks(x)
ax.set_xticklabels(ticks)
ax.set_yticks(y)
ax.set_yticklabels(ticks)
ax.plot(x, y, c='green')
ax.margins(x=0, y=0)
plt.show()
การตั้งค่าขั้นสูง
# ใช้ FixedLocator และ FixedFormatter
from matplotlib.ticker import FixedLocator, FixedFormatter
ax.yaxis.set_major_locator(FixedLocator(y))
ax.yaxis.set_major_formatter(FixedFormatter(ticks))
# หรือใช้ FuncFormatter สำหรับฟังก์ชันกำหนดเอง
from matplotlib.ticker import FuncFormatter
def custom_formatter(val, pos):
return f"Y={val}"
ax.yaxis.set_major_formatter(FuncFormatter(custom_formatter))
เคล็ดลับ
- จำนวน ticks และ labels ต้องเท่ากัน
- ใช้
rotationในset_yticklabels()หากข้อความยาว plt.margins(0)ลบพื้นที่ว่างด้านข้าง- สำหรับ Log scale ใช้
LogLocatorและLogFormatter
การประยุกต์ใช้
เหมาะสำหรับกราฟที่แกน Y เป็นหมวดหมู่ (categorical) การแสดงระดับความเสี่ยง คะแนนเกรด หรือการแปลงหน่วยการวัดให้อ่านง่ายขึ้น