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

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

บทนำ

Stacked Bar Chart แสดงส่วนประกอบสะสมของหลายหมวดหมู่ในแท่งเดียว ใช้ bottom พารามิเตอร์ซ้อนแท่ง

การติดตั้ง

pip install matplotlib

Dependencies

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

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

import matplotlib.pyplot as plt

labels = ['A1', 'A2', 'A3', 'A4']
val_1 = [34, 56, 78, 91]
val_2 = [20, 56, 32, 89]
val_3 = [1, 3, 5, 3]   # error bars for val_1
val_4 = [3, 5, 3, 4]   # error bars for val_2

width = 0.40
fig, ax = plt.subplots()
ax.bar(labels, val_1, width, yerr=val_3, label='Label_1')
ax.bar(labels, val_2, width, yerr=val_4, bottom=val_1, label='Label_2')
ax.set_ylabel('Y-axis')
ax.set_title('X-axis')
ax.legend()
plt.show()

คำอธิบาย

  • แท่งแรก: bar(labels, val_1, ...)

  • แท่งที่สอง: bar(labels, val_2, bottom=val_1, ...) ซ้อนบนแท่งแรก

  • รองรับ Error bars (yerr) ทั้งสองชั้น