ใช้ ax.loglog() สำหรับ Log Scale ทั้ง 2 แกน และ set_major_formatter() กับ LogFormatterExponent เพื่อแสดง Tick เป็นเลขยกกำลัง
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้าง Figure และ Subplots
- Plot ด้วย Log Scale ทั้งคู่ (
ax.loglog) - ตั้งค่า Formatter ให้ Major Ticker
- แสดงผล
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt, ticker
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, ax = plt.subplots()
# ข้อมูล Log Scale: x = 10^0 ถึง 10^5, y = x^2
ax.loglog(np.logspace(0, 5), np.logspace(0, 5)**2)
# แสดง Tick เป็น 10^n
ax.xaxis.set_major_formatter(ticker.LogFormatterExponent())
plt.show()
Formatter อื่นๆ สำหรับ Log Scale
# แสดงเป็น 10^n (ค่าเริ่มต้น)
ax.xaxis.set_major_formatter(ticker.LogFormatterSciNotation())
# แสดงเป็นเลขปกติ (ไม่ใช่ Scientific)
ax.xaxis.set_major_formatter(ticker.LogFormatter())
# Custom Formatter
ax.xaxis.set_major_formatter(ticker.FuncFormatter(
lambda x, pos: f'10^{int(np.log10(x))}'
))
ผลลัพธ์
Log-Log Plot ที่แกน X แสดง Tick Labels เป็นรูปแบบ 10^0, 10^1, 10^2, ... แทนค่าตัวเลขเต็ม