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

วิธีแสดง Pie Chart ด้วย Matplotlib ใน Python

บทนำ

Pie Chart แสดงสัดส่วนข้อมูลเป็นเปอร์เซ็นต์ในวงกลม ใช้ ax.pie()

การติดตั้ง

pip install matplotlib

Dependencies

Python>=3.4, NumPy, Setuptools, Pyparsing, Libpng, Pytz, FreeType, Six, Cycler, Dateutil

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

import matplotlib.pyplot as plt

labels = 'Label_1', 'Label_2', 'Label_3'
sizes = [10, 34, 56]
explode = (0, 0.1, 0)  # ดึง Label_2 ออกมาเน้น

fig1, ax1 = plt.subplots()
ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
ax1.axis('equal')  # ทำให้เป็นวงกลมสมบูรณ์
plt.show()

คำอธิบาย

  • autopct: แสดง % บนแต่ละชิ้น

  • explode: ดึงชิ้นที่ต้องการออกจากศูนย์กลาง

  • shadow=True: เพิ่มเงา

  • axis('equal'): บังคับ Aspect Ratio 1:1