每格点数相等的直方图

2024-03-28 19:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有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


Tags: 代码import数量bin宽度排序matplotlib情况
3条回答

为柱状图提供箱子:

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

然后

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

(前提是对点进行排序)

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

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

这个问题是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=Truekwarg To plt.hist。如我的other answer所述。

相关问题 更多 >