matplotlib创建多组堆叠的直方图

时间:2018-09-11 20:50:55

标签: python matplotlib histogram grouped-table

我想使用此one(成组的堆叠条形图)创建类似的图形:

import numpy as np
import matplotlib.pyplot as plt

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)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
         bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

这只是代替每组堆叠的直方图,而不是每组堆叠的直方图。如此粗略地说,我想将plt.bar更改为plt.hist,并保持图形布局不变。

那样,这就像将多个(相同范围/ bin)直方图放入同一轴的一个图中(不是多个子图图)一样,但是不确定如果它被认为是包含多个的大直方图,是否有帮助子直方图。哪种方法更容易实现?

我将代码here用作MWE,也许您可​​以帮助我将它们复制为3组(同一轴),假设它们是3个不同的直方图。我不在乎在x轴上显示直方图的值,只要组名就足够了。

x1 = mu + sigma*np.random.randn(990,1)
x2 = mu + sigma*np.random.randn(980,1)
x3 = mu + sigma*np.random.randn(1000,1)

#Stack the data
plt.figure()
plt.hist([x1,x2,x3], bins, stacked=True, normed = True)
plt.show()

我将提供一个与我所期望的相似的样地。为了对此进行绘制,我手动移动了第二个和第三个直方图的范围(最初它们与第一个直方图的范围相同),因此显示的x轴有些混乱。如果这是唯一(最简单)的方法,我想将x轴值替换为组名,例如“第1组”,“第2组”,“第3组”。

Link to image

0 个答案:

没有答案