ในการสร้างแผนภูมิแท่งแบบเรียงซ้อนที่แตกต่างกันใน Matplotlib เราสามารถทำตามขั้นตอนต่อไปนี้ -
- กำหนดขนาดรูปและปรับช่องว่างภายในระหว่างและรอบๆ แผนผังย่อย
- เริ่มต้นตัวแปร N เพื่อรับจำนวนดัชนี
- รับ ผู้ชายหมายถึง ผู้หญิงหมายถึง ผู้ชายStd และ ผู้หญิงStd tuple
- เริ่มต้น ความกว้าง ของบาร์
- สร้างร่างและชุดแผนย่อย
- ในการรับแถบแยก เราสามารถใส่ข้อมูลด้วยค่าบวกและค่าลบเพื่อสร้างแท่ง Diverging
- เพิ่มเส้นแนวนอนพาดผ่านแกน
- ตั้งค่า Ylabel, title, ticks, ticklabels, และ ตำนาน
- หากต้องการแสดงรูป ให้ใช้ 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() ผลลัพธ์
