繁体   English   中英

如何使用Python沿x轴对2D数据进行装箱

[英]How to bin a 2D data along the x-axis with Python

我有两个对应的数据数组(x和y),它们在对数-对数图上如上所述进行绘制。 数据目前过于精细,我想对它们进行分类以获得更平滑的关系。 我可以得到一些关于如何沿x轴以指数仓大小进行仓位的指导,以使其在对数-对数刻度上呈线性吗?

例如,如果第一个bin的范围是x = 10 ^ 0到10 ^ 1,我想收集该范围内具有相应x的所有y值,并将它们平均化为该bin的一个值。 我认为np.hist或plt.hist并不能解决问题,因为它们通过计数事件进行合并。

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

您可以使用熊猫来实现。 这个想法是使用np.digitize将每个X值分配给一个间隔。 由于使用的是对数刻度,因此使用np.logspace选择长度呈指数变化的间隔是有意义的。 最后,您可以将每个间隔中的X值分组并计算平均Y值。


import pandas as pd
import numpy as np

x_max = 10

xs = np.exp(x_max * np.random.rand(1000))
ys = np.exp(np.random.rand(1000))

df = pd.DataFrame({
    'X': xs,
    'Y': ys,
})

df['Xbins'] = np.digitize(df.X, np.logspace(0, x_max, 30, base=np.exp(1)))
df['Ymean'] = df.groupby('Xbins').Y.transform('mean')
df.plot(kind='scatter', x='X', y='Ymean')

您可以使用scipy.stats.binned_statistic来获取每个bin中数据的平均值。 最好通过numpy.logspace创建numpy.logspace 然后,您可以绘制这些均值,例如绘制为跨箱宽度的水平线或在平均位置处的散点图。

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()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM