简体   繁体   English

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

[英]How to align two numpy histograms so that they share the same bins/index, and also transform histogram frequencies to probabilities?

How to convert two datasets X and Y to histograms whose x-axes/index are identical, instead of the x-axis range of variable X being collectively lower or higher than the x-axis range of variable Y (like how the code below generates)?如何将两个数据集 X 和 Y 转换为 x 轴/索引相同的直方图,而不是变量 X 的 x 轴范围共同低于或高于变量 Y 的 x 轴范围(如下面的代码如何生成)? I would like the numpy histogram output values to be ready to plot in a shared histogram-plot afterwards.我希望 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)

You need not use np.histogram if your goal is just plotting the two (or more) together.如果您的目标只是将两个(或更多)绘制np.histogram则不需要使用np.histogram Matplotlib can do that. Matplotlib 可以做到这一点。

import matplotlib.pyplot as plt

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

在此处输入图片说明

If you want the probabilities instead of counts in histogram, add weights:如果您想要概率而不是直方图中的计数,请添加权重:

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

You can also get output from plt.hist for some other usage.您还可以从plt.hist获取输出plt.hist用于其他用途。

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

在此处输入图片说明

Note usage of n-1 here instead of n because one extra bin is added by numpy and matplotlib.注意这里使用n-1而不是n因为 numpy 和 matplotlib 添加了一个额外的 bin。 You may use n depending on your use case.您可以根据您的用例使用n

However, if you really want the bins for some other purpose, np.historgram gives the bins used in output - which you can use as input in second histogram:但是,如果您真的想要将 bin 用于其他目的, np.historgram会提供输出中使用的 bin - 您可以将其用作第二个直方图中的输入:

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

Y's bins used for X here because your Y has wider range than X.此处用于 X 的 Y 的 bin 是因为您的 Y 的范围比 X 宽。

Reconciliation Checks:对帐检查:

all(bins_numpy == bins2)

>>>True


all(bins_numpy == bins_plt)

>>>True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM