簡體   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