每个箱中具有相同点数的直方图

时间:2016-09-09 19:18:57

标签: python matplotlib histogram

我有一个100分的排序向量points。我现在想要创建两个直方图:第一个直方图应该有10个具有相等宽度的区间。第二个也应该有10个直方图,但不一定宽度相等。在第二个,我只想让直方图在每个bin中具有相同的点数。因此,例如,第一个柱可能非常短而宽,而直方图中的第二个柱可能非常高而窄。我有使用matplotlib创建第一个直方图的代码,但现在我不知道如何创建第二个直方图。

import matplotlib.pyplot as plt
points = [1,2,3,4,5,6, ..., 99]
n, bins, patches = plt.hist(points, 10)

修改

尝试下面的解决方案,我有点疑惑为什么直方图中所有条形的高度都相同。

enter image description here

4 个答案:

答案 0 :(得分:12)

这个问题是similar to one,我在一段时间之前写了一个答案,但是有足够的不同以保证它自己的问题。事实证明,解决方案使用了与我的其他答案基本相同的代码。

def histedges_equalN(x, nbin):
    npt = len(x)
    return np.interp(np.linspace(0, npt, nbin + 1),
                     np.arange(npt),
                     np.sort(x))

x = np.random.randn(100)
n, bins, patches = plt.hist(x, histedges_equalN(x, 10))

此解决方案为直方图提供了相同的高度分档,因为---根据定义---直方图是每个分档中点数的计数。

要获得pdf(即密度函数),请使用normed=True kwarg来plt.hist。如我other answer中所述。

答案 1 :(得分:0)

provide bins to histogram:

bins=points[0::len(points)/10]

and then

n, bins, patches = plt.hist(points, bins=bins)

(provided points is sorted)

答案 2 :(得分:0)

在这里,我写了一个关于如何获得结果的例子。我的方法使用数据点来获取将传递给np.histogram的二进制位以构建直方图。因此需要使用np.argsort(x)对数据进行排序。每个箱的点数可以用npoints来控制。作为示例,我使用此方法构造两个直方图。所有点的权重相同的一个,以使直方图的高度始终恒定(并且等于npoints)。另一个是每个点的“权重”来自均匀随机分布(参见mass数组)。正如所料,直方图的框不再相等。但是,每个bin的泊松误差是相同的。

x = np.random.rand(1000)
mass = np.random.rand(1000)
npoints = 200
ksort = np.argsort(x)

#Here I get the bins from the data set.
#Note that data need to be sorted
bins=x[ksort[0::npoints]]
bins=np.append(bins,x[ksort[-1]])


fig = plt.figure(1,figsize=(10,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

#Histogram where each data 
yhist, xhist = np.histogram(x, bins, weights=None)
ax1.plot(0.5*(xhist[1:]+xhist[:-1]), yhist, linestyle='steps-mid', lw=2, color='k')

yhist, xhist = np.histogram(x, bins, weights=mass)
ax2.plot(0.5*(xhist[1:]+xhist[:-1]), yhist, linestyle='steps-mid', lw=2, color='k')

ax1.set_xlabel('x', size=15)
ax1.set_ylabel('Number of points per bin', size=15)

ax2.set_xlabel('x', size=15)
ax2.set_ylabel('Mass per bin', size=15)

enter image description here

答案 3 :(得分:0)

此解决方案不那么优雅,但对我有用。希望对您有帮助

LinearLayout
相关问题