1

如何将两个数据集 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)
4

1 回答 1

1

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

import matplotlib.pyplot as plt

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

在此处输入图像描述

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

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()

在此处输入图像描述

注意这里的用法,n-1而不是n因为 numpy 和 matplotlib 添加了一个额外的 bin。您可以n根据您的用例使用。

但是,如果您真的想要这些 bin 用于其他目的,np.historgram请给出输出中使用的 bin - 您可以将其用作第二个直方图中的输入:

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
于 2020-11-02T16:43:57.740 回答