如何对齐两个numpy直方图,以便它们共享相同的bin/index,并将直方图频率转换为概率? [英] How to align two numpy histograms so that they share the same bins/index, and also transform histogram frequencies to probabilities?

查看:144
本文介绍了如何对齐两个numpy直方图,以便它们共享相同的bin/index,并将直方图频率转换为概率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)? I would like the numpy histogram output values to be ready to plot in a shared histogram-plot afterwards.

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可以做到这一点.

You need not use np.histogram if your goal is just plotting the two (or more) together. Matplotlib can do that.

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)

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

You can also get output from plt.hist for some other usage.

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

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

Note usage of n-1 here instead of n because one extra bin is added by numpy and matplotlib. You may use n depending on your use case.

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

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:

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

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

Y's bins used for X here because your Y has wider range than X.

对帐检查:

all(bins_numpy == bins2)

>>>True


all(bins_numpy == bins_plt)

>>>True

这篇关于如何对齐两个numpy直方图,以便它们共享相同的bin/index,并将直方图频率转换为概率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆