具有在 numpy 数组中定义的 bin 高度的堆叠直方图

Stacked histogram with bin heights defined in numpy array

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

例如,我有 12 个 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 实现吗?

权重参数会为您解决这个问题。将单个数据点放入每个桶中,然后通过指定其权重来控制高度

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)

如果您的垃圾桶不是等间距的,它们的厚度就会开始不同,但除此之外,这应该可以解决您的问题。