首页 > 解决方案 > 每个 bin 中数据的“标签分数”的 2D 直方图颜色

问题描述

继此处找到的帖子之后:在每个 bin 中按标准差着色的 2D 直方图

我想通过标签值低于 Python 中某个阈值的点的分数来为 2D 网格中的每个 bin 着色。

请注意,在此数据集中,每个点都有一个介于 0-1 之间的连续标签值。

例如,这是我制作的直方图,其中颜色表示每个 bin 中所有点的标签值的标准偏差:

在此处输入图像描述

这样做的方法是使用

scipy.stats.binned_statistic_2d()

(见:https ://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.binned_statistic_2d.html )

..并将统计参数设置为“std”

但是有没有办法改变这种图,以便着色代表每个 bin 中标签值低于 0.5 的点的分数?

这样做的唯一方法可能是明确定义某种网格并计算分数,但我不确定最好的方法,所以在这个问题上的任何帮助将不胜感激!

也许使用 scipy.stats.binned_statistic_2d 或 numpy.histogram2d 并能够将每个 bin 中的原始数据值作为多维数组返回将有助于能够快速明确地计算分数。

标签: pythonmatplotlibscipyhistogrambinning

解决方案


数组中低于阈值的元素比例可以计算为

fraction = lambda a, threshold: len(a[a<threshold])/len(a)

因此你可以打电话

scipy.stats.binned_statistic_2d(x, y, values, statistic=lambda a: fraction(a, 0.5)) 

推荐阅读