繁体   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