python - 针对概率标准化的二维直方图
问题描述
我有一个二维数据集,我想绘制一个二维直方图,直方图上的每个单元格代表数据点的概率。因此,为了获得概率,我需要对直方图数据进行归一化,使其总和为 1。以下是我的示例,来自 2Dhistogram 文档:
xedges = [0,1,3,5]
yedges = [0,2,3,4,6]
#create edges of bins
#create random data points
x=np.random.normal(2,1,100)
y=np.random.normal(1,1,100)
H,xedges,yedges = np.histogram2d(x,y,bins=(xedges,yedges))
#setting normed=True in histogram2d doesn't seem to do what I need
H=H.T
#weirdly histogram2d swaps the x,y axis, so transpose to restore it.
fig = plt.figure(figsize=(7,3))
plt.imshow(H,interpolation='nearest',origin='low',extent=[xedges[0], xedges[-1],yedges[0],yedges[-1]])
plt.show()
首先,anp.sum(H)
给出类似 86 的值。我希望每个单元格代表数据位于该分箱单元格上的概率,因此它们的总和应为 1。此外,您如何绘制将颜色强度映射到其值的图例imshow
?
谢谢!
解决方案
尝试使用normed
参数。此外,根据文档, H 中的值将计算为bin_count / sample_count / bin_area
。因此,我们计算箱的面积并将其乘以 H 以获得箱的概率。
xedges = [0,1,3,5]
yedges = [0,2,3,4,6]
# create edges of bins
x = np.random.normal(2, 1, 100) # create random data points
y = np.random.normal(1, 1, 100)
H, xedges, yedges = np.histogram2d(x, y, bins=(xedges, yedges), normed=True)
areas = np.matmul(np.array([np.diff(xedges)]).T, np.array([np.diff(yedges)]))
# setting normed=True in histogram2d doesn't seem to do what I need
fig = plt.figure(figsize=(7, 3))
im = plt.imshow(H*areas, interpolation='nearest', origin='low', extent=[xedges[0], xedges[-1], yedges[0], yedges[-1]])
plt.colorbar(im)
plt.show()
推荐阅读
- javascript - Axios 请求在 iOS 上显示响应但不适用于 android
- wordpress - 如何 301 重定向特定页面以删除部分 URL?
- html - 如何使用
- jquery - 出于安全考虑,是否有类似于 End of Life/Supported Versions 的 jQuery 版本的支持终止
- python - 哪个 Pandas 数据框更好:超长数据框 VS 结构不良的带有列表的数据框
- python - 如何在python代码中获取mnist数据集的错误接受率和错误拒绝率之间的图表
- typescript - 条件类型添加一个额外的泛型得到编译器错误
- php - 有什么具体的方法来编写 click house curl 插入查询吗?
- c - C中的单指针与双指针
- python - 如何使用 df.iterrows() 匹配同一列中的前一行值?