ใช้ ax.set_xticklabels(x.astype(int)) แปลงค่า Tick Labels เป็น Integer
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างข้อมูล X, Y แบบ Float
- สร้าง Figure และ Axes
- Plot ข้อมูล
- ตั้งค่า Xtick Labels ให้เป็น Integer
- แสดงผล
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([1.110, 2.110, 4.110, 5.901, 6.00, 7.90, 8.90])
y = np.array([2.110, 1.110, 3.110, 9.00, 4.001, 2.095, 5.890])
fig, ax = plt.subplots()
ax.plot(x, y)
# แปลง X Tick Labels เป็น Integer
ax.set_xticklabels(x.astype(int))
plt.show()
วิธีอื่นๆ
# ใช้ Formatter
from matplotlib.ticker import FuncFormatter
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, _: int(x)))
# ใช้ MaxNLocator กับ integer=True
from matplotlib.ticker import MaxNLocator
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
# Format String
ax.xaxis.set_major_formatter('{x:.0f}')
ผลลัพธ์
กราฟเส้น แกน X แสดงตัวเลขจำนวนเต็ม 1, 2, 4, 6, 6, 7, 9 (ตัดทศนิยมทิ้ง)