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

วิธีแสดงจำนวนนับ (Count) บนแท่ง Histogram ใน Matplotlib

การแสดงค่า Count บนแท่ง Histogram

วนลูปผ่าน patches จาก hist() ใช้ text() วางค่าที่กลางบนแต่ละแท่ง

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • เตรียมข้อมูล list สำหรับ histogram
  • เรียก hist() รับคืน patches
  • วนลูป patches คำนวณตำแหน่งกลาง x และความสูง y
  • ใช้ plt.text(x, y, count) วางข้อความ
  • แสดงผลด้วย show()

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

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [3, 5, 1, 7, 9, 5, 3, 7, 5]
_, _, patches = plt.hist(data, align="mid")

for pp in patches:
    x = (pp._x0 + pp._x1) / 2
    y = pp._y1 + 0.05
    plt.text(x, y, int(pp._y1))

plt.show()

คำอธิบาย

  • pp._x0, pp._x1: ขอบซ้าย/ขวาของแท่ง
  • pp._y1: ความสูงของแท่ง (count)
  • y + 0.05 ยกข้อความขึ้นเล็กน้อยเหนือแท่ง