首页 > 解决方案 > matplotlib 创建多组堆叠直方图

问题描述

我想用这个创建类似的图表堆叠条形图组):

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.barplt.hist并保持图形布局不变。

这样,就像将多个(相同范围/ bin)直方图放入同一轴的一个图中(不是多个子图图),但不确定是否可以将其视为包含多个子直方图的大直方图. 哪种方式更容易接近?

我在这里使用代码作为 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”。

链接到图片

标签: pythonmatplotlibhistogramgrouped-table

解决方案


推荐阅读