首页 > 解决方案 > 如何使用 Python 沿 x 轴分箱 2D 数据

问题描述

我有两个相应的数据数组(x 和 y),我在对数图上绘制如上。数据目前过于精细,我想将它们分箱以获得更平滑的关系。我能否获得一些关于如何沿 x 轴以指数bin 大小进行 bin 的指导,以使其在 log-log 尺度上呈现线性?

例如,如果第一个 bin 的范围为 x = 10^0 到 10^1,我想收集该范围内具有相应 x 的所有 y 值,并将它们平均为该 bin 的一个值。我不认为 np.hist 或 plt.hist 完全可以解决问题,因为它们通过计数出现来进行分箱。

编辑:对于上下文,如果有帮助,上面的图是一个分类图,它绘制了某个网络的进出度。

标签: pythonnumpymatplotlibhistogrambinning

解决方案


您可以使用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()

在此处输入图像描述


推荐阅读