ในการสร้าง Diverging Stacked Bar Chart ใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้:
- ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
- เริ่มต้นตัวแปร N เพื่อรับจำนวนดัชนี
- รับ menMeans, womenMeans, menStd และ womenStd tuple
- เริ่มต้น width ของแท่ง
- สร้าง figure และชุด subplots
- เพื่อให้ได้ diverging bar เราสามารถวางข้อมูลด้วยค่าบวกและลบเพื่อทำ diverging bars
- เพิ่มเส้นแนวนอนข้ามแกน
- ตั้งค่า Ylabel, title, ticks, ticklabels, และ legend
- เพื่อแสดงรูป ใช้เมธอด show()
ตัวอย่าง
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
N = 5
menMeans = (20, -35, 30, 35, -27)
womenMeans = (25, -32, 34, 20, -25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)
width = 0.35
fig, ax = plt.subplots()
p1 = ax.bar(ind, menMeans, width, yerr=menStd, label='Men')
p2 = ax.bar(ind, womenMeans, width, bottom=menMeans, yerr=womenStd, label='Women')
ax.axhline(0, color='grey', linewidth=0.8)
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend()
plt.show()
ผลลัพธ์
