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

วิธีแสดงค่าจริงบน Pie Chart ใน Matplotlib

การแสดงค่าจริงแทนเปอร์เซ็นต์บน Pie Chart

ปกติ pie chart จะแสดงเปอร์เซ็นต์ แต่สามารถปรับให้แสดงค่าจริงได้ด้วย autopct

ขั้นตอนหลัก

  • ตั้งค่าขนาดรูปและ padding
  • เตรียม labels, fractions, explode position และคำนวณผลรวม
  • สร้าง pie chart ด้วย autopct=lambda p: '{:.0f}%'.format(p * total / 100)
  • แสดงผลด้วย show()

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

import matplotlib.pyplot as plt

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

labels = ('Read', 'Eat', 'Sleep', 'Repeat')
fracs = [5, 3, 4, 1]
total = sum(fracs)
explode = (0, 0.05, 0, 0)

plt.pie(fracs, explode=explode, labels=labels,
        autopct=lambda p: '{:.0f}%'.format(p * total / 100),
        shadow=True, startangle=90)
plt.show()

คำอธิบาย

lambda function คำนวณค่าจริงจากเปอร์เซ็นต์ p โดยใช้สูตร p * total / 100