如何对齐两个numpy直方图,以便它们共享相同的bin / index,并将直方图频率转换为概率?

问题描述

如何将两个数据集X和Y转换为x轴/索引相同的直方图,而不是将变量X的x轴范围统称为低于或高于变量Y的x轴范围(例如下面的代码生成)?我希望将numpy直方图的输出值事后准备在共享的直方图中绘制。

import numpy as np
from numpy.random import randn

n = 100  # number of bins

#datasets
X = randn(n)*.1
Y = randn(n)*.2

#empirical distributions
a = np.histogram(X,bins=n)
b = np.histogram(Y,bins=n)

解决方法

如果您的目标只是将两个(或多个)绘制在一起,则无需使用np.histogram。 Matplotlib可以做到这一点。

import matplotlib.pyplot as plt

plt.hist([X,Y])  # using your X & Y from question
plt.show()

enter image description here

如果您想要概率而不是直方图中的计数,请添加权重:

wx = np.ones_like(X) / len(X)
wy = np.ones_like(Y) / len(Y)

您还可以从plt.hist获取输出以用于其他用途。

n_plt,bins_plt,patches = plt.hist([X,Y],bins=n-1,weights=[wx,wy])  
plt.show()

enter image description here

请注意此处使用n-1而不是n,因为numpy和matplotlib添加了一个额外的bin。您可以根据自己的使用情况使用n

但是,如果您确实希望将垃圾箱用于其他用途,则np.historgram会提供用于输出的垃圾箱-您可以将其用作第二个直方图中的输入:

a,bins_numpy = np.histogram(Y,bins=n-1)
b,bins2 = np.histogram(X,bins=bins_numpy)

这里的Y用于X的垃圾箱,因为您的Y的范围比X大。

对帐检查:

all(bins_numpy == bins2)

>>>True


all(bins_numpy == bins_plt)

>>>True