在numpy数组中定义的bin高度的堆积直方图

时间:2015-04-18 00:49:05

标签: python numpy matplotlib

我想用numpy数组创建堆积直方图,其条目是所需的bin高度。

例如,我有十二个分区:

bins = np.linspace(0,120,13)

我有几个numpy数组,每个数组有12个元素(每个bin 1个):

hist1 = [1.1,2.2,3.3,4.4,......,hist1[11]]
hist2 = [9.9,8.8,7.7,6.6,......,hist2[11]]

我想变成堆积直方图。 matplotlib可以吗?

1 个答案:

答案 0 :(得分:1)

权重参数将为您解决此问题。在每个桶中放置一个数据点,然后通过指定其重量来控制高度

import numpy as np
import matplotlib.pyplot as plt

bins = np.linspace(0,120,13)


# my approximation of your example arrays
hist1 = np.arange(1.1,15, 1.1)
hist2 = np.arange(15, 1.1, -1.1)

all_weights = np.vstack([hist1, hist2]).transpose()
all_data = np.vstack([bins, bins]).transpose()
num_bins = len(bins)

plt.hist(x = all_data, bins = num_bins, weights = all_weights, stacked=True, align = 'mid', rwidth = .5)

如果您的垃圾箱间距不均匀,它们的厚度会有所不同,但除此之外,这应该可以解决您的问题。 enter image description here