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

inq*_*ies 3 database matplotlib normalization histogram bar-chart

我将不胜感激以下任何见解。

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

让我解释一下我的意思。到目前为止,我可以很好地绘制一个直方图的两个数据集,并迫使这两个分布的积分写为1normed = 1ax.hist(),如下面的图所示: 在此处输入图片说明

它是由这样的代码产生的:

        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)             
Run Code Online (Sandbox Code Playgroud)

在一般情况下,一种概率分布比另一种高得多,这使得很难清楚地阅读图。

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

for item in patches1:
    item.set_height(item.get_height()/sum(x1))
Run Code Online (Sandbox Code Playgroud)

这是取自这里的讨论如何在 python 中规范化直方图?,但 python 向我抛出一条错误消息,说没有这样的质量get_height.

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

Tho*_*ühn 8

我建议使用预先计算直方图numpy,然后在matplotlibusing 中绘制它们bar。然后可以通过除以每个直方图的最大幅度来简单地对直方图进行归一化(按幅度)。请注意,为了在两个直方图之间进行任何有意义的比较,最好对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()
Run Code Online (Sandbox Code Playgroud)

以及这看起来如何的图片:

在此处输入图片说明

希望这可以帮助。