簡體   English   中英

如何使用堆疊條形圖繪制兩個直方圖,而不將所有條形圖堆疊在一起?

[英]how to plot two histograms with stacked bars, without stacking all the bars together?

我有4個直方圖,比方說A,B,C和D.我想將直方圖A和B一起繪制,帶有堆疊條,以及直方圖C和D,也有堆疊條,但沒有將四個直方圖堆疊在一起。 所以我想在一個直方圖中使用並排條形圖的兩個堆疊直方圖。

到目前為止,我可以繪制帶有疊條的ABCD; 或AB和CD在不同的堆疊直方圖中,但兩個直方圖的條不是並排的。 是我的代碼:

plot=[A,B,C,D] #values from 0-10
ww=[wA,wB,wC,wD] #weights

所有酒吧堆疊:

plt.hist(plot,bins=10,weights=ww,label=['A','B','C','D'],histtype="barstacked")

AB直方圖+ CD直方圖,但一個直方圖隱藏另一個:

plt.hist(plot[0:2],bins=10,weights=ww[0:2],label=['loses','wins'],stacked=True)
plt.hist(plot[2:4],bins=10,weights=ww[2:4],label=['l','w'],stacked=True)

在此先感謝您的幫助!

你可以使用hist()返回的補丁列表:

import numpy as np
import matplotlib.pyplot as plt
A = np.arange(100)
B = np.arange(100)
C = np.arange(100)
D = np.arange(100)

wA = np.abs(np.random.normal(size=100))
wB = np.abs(np.random.normal(size=100))
wC = np.abs(np.random.normal(size=100))
wD = np.abs(np.random.normal(size=100))

plot=[A,B,C,D] #values from 0-10
ww=[wA,wB,wC,wD] #weights

n, bins, patches = plt.hist(plot[0:2],bins=10,weights=ww[0:2],label=['loses','wins'],stacked=True)
n, bins, patches2 = plt.hist(plot[2:4],bins=10,weights=ww[2:4],label=['l','w'],stacked=True)

for patch in patches:
    plt.setp(patch, 'width', 10)
for patch in patches2:
    plt.setp(patch, 'width', 5)    

plt.show()

直方圖

更新

我發現有一個更好,更清潔的方法來做到這一點:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

# the data
A = np.arange(10)
B = np.arange(10)
C = np.arange(10)
D = np.arange(10)

wA = np.abs(np.random.normal(size=10))
wB = np.abs(np.random.normal(size=10))
wC = np.abs(np.random.normal(size=10))
wD = np.abs(np.random.normal(size=10))
## necessary variables
width = 0.5                      # the width of the bars
## the bars
rects1 = ax.bar(A - width/2, wA, width,
                color='blue')
rects2 = ax.bar(B- width/2, wB, width, bottom=wA,
                color='green')
rects3 = ax.bar(C + width/2, wC, width,
                color='red')
rects4 = ax.bar(D + width/2, wD, width, bottom=wC,
                color='yellow')
# axes and labels
ax.set_xlim(-width,len(A)+width)

plt.show()

結果呢: 更好的直方圖

有關詳細信息,請查看此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM