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

วิธีแสดงเปอร์เซ็นต์เหนือแท่งใน Bar Chart ของ Matplotlib


ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้างข้อมูล x และ y เริ่มต้นตัวแปร width
  • สร้าง figure และชุด subplots ด้วย subplots()
  • เพิ่มแท่งด้วยข้อมูล x และ y
  • วนลูป patches ของแท่ง วางข้อความเหนือแท่งด้วย text()
  • ใช้เมธอด show() เพื่อแสดงรูปภาพ

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

from matplotlib import pyplot as plt
import numpy as np

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

x = [1, 2, 3, 4, 5]
y = [3, 4, 2, 1, 3]
width = 0.35
fig, ax = plt.subplots()
pps = ax.bar(x, y, width, align='center')
for p in pps:
    height = p.get_height()
    ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,
        s="{}%".format(height),
        ha='center')
plt.show()

ผลลัพธ์

วิธีแสดงเปอร์เซ็นต์เหนือแท่งใน Bar Chart ของ Matplotlib