python - 如何使用 Python 沿 x 轴分箱 2D 数据
问题描述
我有两个相应的数据数组(x 和 y),我在对数图上绘制如上。数据目前过于精细,我想将它们分箱以获得更平滑的关系。我能否获得一些关于如何沿 x 轴以指数bin 大小进行 bin 的指导,以使其在 log-log 尺度上呈现线性?
例如,如果第一个 bin 的范围为 x = 10^0 到 10^1,我想收集该范围内具有相应 x 的所有 y 值,并将它们平均为该 bin 的一个值。我不认为 np.hist 或 plt.hist 完全可以解决问题,因为它们通过计数出现来进行分箱。
编辑:对于上下文,如果有帮助,上面的图是一个分类图,它绘制了某个网络的进出度。
解决方案
您可以使用scipy.stats.binned_statistic
来获取每个 bin 中数据的平均值。垃圾箱最好通过numpy.logspace
. 然后,您可以将这些均值绘制为跨越 bin 宽度的水平线或平均位置处的散点图。
import numpy as np; np.random.seed(42)
from scipy.stats import binned_statistic
import matplotlib.pyplot as plt
x = np.logspace(0,5,300)
y = np.logspace(0,5,300)+np.random.rand(300)*1.e3
fig, ax = plt.subplots()
ax.scatter(x,y, s=9)
s, edges, _ = binned_statistic(x,y, statistic='mean', bins=np.logspace(0,5,6))
ys = np.repeat(s,2)
xs = np.repeat(edges,2)[1:-1]
ax.hlines(s,edges[:-1],edges[1:], color="crimson", )
for e in edges:
ax.axvline(e, color="grey", linestyle="--")
ax.scatter(edges[:-1]+np.diff(edges)/2, s, c="limegreen", zorder=3)
ax.set_xscale("log")
ax.set_yscale("log")
plt.show()
推荐阅读
- python - os.path 和 dataframe.to_csv 找不到 Python 路径字符串
- google-app-engine - 将 Google Cloud Storage 存储桶连接到 App Engine 中的 Docker 映像
- sharepoint - Sharepoint 列表查找列未正确显示标题
- apache - Apache .htaccess 不允许网站访问受限文件夹中的资产
- r - 将列中的字符串拆分为两列
- asp.net - 使用 ZXing 的 QRcode(纠错问题)
- environment-variables - Wampserver 升级:环境变量错误
- c# - 如何将 Class 属性添加到 MVC 中的自定义 Html Helper 中?
- mysql - 内部联接在哪里查询中显示错误的日期?
- php - Magento 结帐第二条额外成功消息