在同一图中标准化两个直方图

问题描述 投票:1回答:1

我将非常感谢以下任何见解。

我想在一个公共直方图上绘制两个数据集,这样两个直方图都没有截止顶部,概率分布范围从0到1。

让我解释一下我的意思。到目前为止,我可以很好地在一个直方图上绘制两个数据集,并通过在normed = 1中编写ax.hist()来强制两个分布的积分为1,如下图所示:enter image description here

这是由以下代码生成的:

        x1, w1, patches1 = ax.hist(thing1, bins=300, edgecolor='b', color='b', histtype='stepfilled', alpha=0.2, normed = 1)

        x2, w2, patches2 = ax.hist(thing2, bins=300, edgecolor='g', color='g', histtype='stepfilled', alpha=0.2, normed = 1)             

在一般情况下,一个概率分布远高于另一个概率分布,这使得难以清楚地阅读该图。

所以,我试图对两者进行归一化,使得它们在y轴上的范围从0到1并且仍然保持它们的形状。例如,我尝试了以下代码:

for item in patches1:
    item.set_height(item.get_height()/sum(x1))

这是从How to normalize a histogram in python?的讨论中获取的,但是python抛出了一条错误消息,说没有像get_height这样的质量。

我的问题很简单:我怎样才能使y轴的范围从0到1并保持两种分布的形状?

database matplotlib histogram bar-chart normalization
1个回答
2
投票

我建议使用numpy预先计算直方图,然后使用matplotlibbar中绘制它们。然后可以通过除以每个直方图的最大幅度简单地对直方图进行归一化(通过幅度)。请注意,为了在两个直方图之间进行任何有意义的比较,最好对它们使用相同的bins。下面的示例如何执行此操作:

from matplotlib import pyplot as plt
import numpy as np

##some random distribution
dist1 = np.random.normal(0.5, 0.25, 1000)
dist2 = np.random.normal(0.8, 0.1, 1000)

##computing the bin properties (same for both distributions)
num_bin = 50
bin_lims = np.linspace(0,1,num_bin+1)
bin_centers = 0.5*(bin_lims[:-1]+bin_lims[1:])
bin_widths = bin_lims[1:]-bin_lims[:-1]

##computing the histograms
hist1, _ = np.histogram(dist1, bins=bin_lims)
hist2, _ = np.histogram(dist2, bins=bin_lims)

##normalizing
hist1b = hist1/np.max(hist1)
hist2b = hist2/np.max(hist2)

fig, (ax1,ax2) = plt.subplots(nrows = 1, ncols = 2)

ax1.bar(bin_centers, hist1, width = bin_widths, align = 'center')
ax1.bar(bin_centers, hist2, width = bin_widths, align = 'center', alpha = 0.5)
ax1.set_title('original')

ax2.bar(bin_centers, hist1b, width = bin_widths, align = 'center')
ax2.bar(bin_centers, hist2b, width = bin_widths, align = 'center', alpha = 0.5)
ax2.set_title('ampllitude-normalized')

plt.show()

以及如何看待这样的图片:

enter image description here

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.