การแสดงค่าตัวเลขหรือข้อความเหนือแท่งในแผนภูมิแท่ง สามารถทำได้โดยใช้เมธอด plt.text() วนลูปผ่านตำแหน่ง X, Y และค่าที่ต้องการแสดง
ขั้นตอนการทำงาน
- เตรียมข้อมูล: รายการหมวดหมู่ (
x), ค่าความสูง (y), และข้อความ/เปอร์เซ็นต์ (percentage) - สร้างแผนภูมิแท่งด้วย
plt.bar(x, y) - วนลูปด้วย
zip(x, y, percentage)เพื่อวางข้อความที่ตำแหน่งแต่ละแท่ง - ใช้
plt.text(x, y, p)โดย:x- ตำแหน่งแนวนอน (ตรงกลางแท่ง)y- ตำแหน่งแนวตั้ง (ยอดแท่ง)p- ข้อความที่จะแสดง
- แสดงผลด้วย
plt.show()
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = ['A', 'B', 'C', 'D', 'E']
y = [1, 3, 2, 0, 4]
percentage = [10, 30, 20, 0, 40]
ax = plt.bar(x, y)
for x_val, y_val, p in zip(x, y, percentage):
plt.text(x_val, y_val, p)
plt.show()
การปรับแต่งตำแหน่งและรูปแบบข้อความ
# วางข้อความเหนือแท่งเล็กน้อย และจัดกึ่งกลาง
for x_val, y_val, p in zip(x, y, percentage):
plt.text(x_val, y_val + 0.1, f"{p}%", ha='center', va='bottom', fontsize=12, fontweight='bold')
# ใช้ offset แบบ relative กับขนาดแท่ง
for x_val, y_val, p in zip(x, y, percentage):
plt.text(x_val, y_val * 1.02, str(p), ha='center', va='bottom')
พารามิเตอร์สำคัญของ plt.text()
ha(horizontal alignment):'center','left','right'va(vertical alignment):'bottom','top','center','baseline'fontsize,fontweight,color,rotationbbox- เพิ่มกล่องพื้นหลัง:bbox=dict(facecolor='white', edgecolor='none', alpha=0.7)
การใช้งานกับ Barh (แท่งแนวนอน)
plt.barh(y, x) # สลับแกน
for i, (x_val, y_val, p) in enumerate(zip(x, y, percentage)):
plt.text(x_val + 0.1, i, str(p), va='center')
การประยุกต์ใช้
เหมาะสำหรับรายงานธุรกิจ การแสดงสถิติการสำรวจ แดชบอร์ด KPI หรือกราฟที่ต้องการให้อ่านค่าได้แม่นยำโดยไม่ต้องมองดูแกน Y