【问题标题】:how to plot two histograms with stacked bars, without stacking all the bars together?如何绘制两个带有堆叠条的直方图,而不将所有条堆叠在一起?
【发布时间】:2019-06-14 07:10:55
【问题描述】:

我有 4 个直方图,比如说 A、B、C 和 D。我想将直方图 A 和 B 与堆叠条一起绘制,以及直方图 C 和 D 以及堆叠条,但不堆叠四个直方图在一起。所以我想在一个带有并排条形的直方图中有两个堆叠的直方图。

到目前为止,我可以绘制带有堆叠条的 A-B-C-D;或不同堆叠直方图中的 A-B 和 C-D,但两个直方图的条形不是并排的。是我的代码:

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")

A-B 直方图 + C-D 直方图,但一个直方图隐藏另一个:

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)

提前感谢您的帮助!

【问题讨论】:

  • 你在使用哪个 python 库? pyplot?

标签: python histogram stacked-chart


【解决方案1】:

你可以使用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()

结果呢:

更多详情请查看this link

【讨论】:

  • 谢谢,差不多!在这种情况下,我们仍然可以在任何地方看到橙色,而我原本期望只看到绿色-红色(例如 A-B)和蓝橙色列(例如 C-D)。例如,有没有办法不仅设置“宽度”,还设置“起点”?这可以解决问题。我的想法是将 A-B 的堆叠直方图与 C-D 的堆叠直方图进行比较,所以如果可能的话,我想避免将橙色放在绿红色的顶部。有什么想法吗?
  • 所以我做了一些更多的研究,有一个更好的方法可以做到这一点,它就像你刚才描述的那样。希望能帮助到你。欢呼;)
  • 太好了!!非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2022-01-16
  • 2014-03-12
相关资源
最近更新 更多