วิธีการวาดฮิสโตแกรมแบบเรียงซ้อนกันสองตัวด้วย Matplotlib / Seaborn
ฉันกำลังวาดฮิสโตแกรมที่ซ้อนกันสองสามตัวโดยใช้รหัสด้านล่าง ฉันใช้ขอบถังเดียวกันสำหรับทั้งสองอย่างเพื่อให้มันจัดชิดกันอย่างดี
ฉันจะแสดงสิ่งเหล่านี้ในแผนภูมิเดียวกันได้อย่างไร? ได้แก่ แถบสีเขียว / แดงและแถบสีฟ้า / ส้มต่อแต่ละถัง - เคียงข้างกัน
ฉันเห็นคำถามและคำตอบมากมายที่คล้ายกับการแนะนำให้ใช้แผนภูมิแท่งและการคำนวณความกว้างของแท่ง แต่ดูเหมือนว่าสิ่งนี้ควรได้รับการสนับสนุนนอกกรอบอย่างน้อยก็ใน matplotlib
นอกจากนี้ฉันสามารถวาดฮิสโตแกรมแบบเรียงซ้อนกับทะเลได้โดยตรงหรือไม่? ฉันไม่สามารถหาทางได้
plt.hist( [correct_a, incorrect_a], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)

plt.hist( [correct_b, incorrect_b], bins=edges, stacked=True, color=['green', 'red'], rwidth=0.95, alpha=0.5)

คำตอบ
ฉันคิดว่าplt.barเป็นทางออกที่ดีที่สุดของคุณที่นี่ ในการสร้างฮิสโทแกรมแบบเรียงซ้อนคุณสามารถใช้bottom
อาร์กิวเมนต์ได้ หากต้องการแสดงแผนภูมิแท่งสองรายการแบบเคียงข้างกันคุณสามารถเปลี่ยนx
ค่าโดยบางค่าได้width
เช่นเดียวกับในตัวอย่าง matplotlib ดั้งเดิมนี้ :
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(16, 8))
correct_a = np.random.randint(0, 20, 20)
incorrect_a = np.random.randint(0, 20, 20)
correct_b = np.random.randint(0, 20, 20)
incorrect_b = np.random.randint(0, 20, 20)
edges = len(correct_a)
width=0.35
rects1 = ax.bar(np.arange(edges), incorrect_a, width, color="red", label="incorrect_a")
rects2 = ax.bar(np.arange(edges), correct_a, width, bottom=incorrect_a, color='seagreen', label="correct_a")
rects3 = ax.bar(np.arange(edges) + width, incorrect_b, width, color="blue", label="incorrect_b")
rects4 = ax.bar(np.arange(edges) + width, correct_b, width, bottom=incorrect_b, color='orange', label="correct_b")
# placing the ticks to the middle
ticks_aligned = np.arange(edges) + width // 2
ax.set_xticks(np.arange(edges) + width / 2)
ax.set_xticklabels((str(tick) for tick in ticks_aligned))
ax.legend()
ผลตอบแทนนี้:
นี่คือตัวอย่างง่ายๆ (ฮิสโตแกรมไม่ซ้อนกัน) สำหรับ 2 ฮิสโตแกรมที่แสดงพร้อมกันโดยที่ถังแต่ละอันจะมีตำแหน่งเฉพาะสำหรับแต่ละฮิสโตแกรมเคียงข้างกัน
# generating some data for this example:
a = [1,2,3,4,3,4,2,3,4,5,4,3,4,5,4,1,2,3,2,1,3,4,5,6,7,6,5,4,3,4,6,5,4,3,4]
b = [1,2,3,4,5,6,7,6,5,6,7,6,5,4,3,4,5,6,7,6,7,6,7,5,4,3,2,1,3,4,5,6,5,6,5,6,7,6,7]
# plotting 2 histograms with bars centered differently within each bin:
plt.hist(a, bins=5, align='left', rwidth=0.5)
plt.hist(b, bins=5, align='mid', rwidth=0.5, color='r')