在x范围内运行y值的中值

2024-10-01 11:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用两个纽比阵列构建的散点图。在

散点图示例 enter image description here

我想在这张图上加上一个y在x范围内的运行中值。我用photoshoped举了一个例子:

修正散点图 enter image description here

具体来说,我需要两个值之间沿x轴以1个单位为单位的数据点的中值(这个范围在许多绘图中会有所不同,但我可以手动调整)。我很感激任何能给我指明方向的建议。在


Tags: 数据绘图示例单位手动建议例子指明方向
3条回答

这个问题也可以通过python pandas(Python数据分析库)有效地解决,它提供了本地的数据切割和分析方法。在

想想这个

(我从他的例子中借用了X和{}的例子,向@Hooked致敬)

 import pandas as pd
 df = pd.DataFrame({'X' : X, 'Y' : Y})  #we build a dataframe from the data

 data_cut = pd.cut(df.X,bins)           #we cut the data following the bins
 grp = df.groupby(by = data_cut)        #we group the data by the cut

 ret = grp.aggregate(np.median)         #we produce an aggregate representation (median) of each bin

 #plotting

 plt.scatter(df.X,df.Y,color='k',alpha=.2,s=2)
 plt.plot(ret.X,ret.Y,'r--',lw=4,alpha=.8)
 plt.show()

备注:此处红色曲线的x值为按箱的x-中间值(可以使用箱子的中点)。在

enter image description here

我会用^{}为你做垃圾箱分类。通过这种方式,您可以轻松地应用任何函数并设置您感兴趣的范围。在

import numpy as np
import pylab as plt

N = 2000
total_bins = 10

# Sample data
X = np.random.random(size=N)*10
Y = X**2 + np.random.random(size=N)*X*10

bins = np.linspace(X.min(),X.max(), total_bins)
delta = bins[1]-bins[0]
idx  = np.digitize(X,bins)
running_median = [np.median(Y[idx==k]) for k in range(total_bins)]

plt.scatter(X,Y,color='k',alpha=.2,s=2)
plt.plot(bins-delta/2,running_median,'r--',lw=4,alpha=.8)
plt.axis('tight')
plt.show()

enter image description here

作为方法多功能性的一个例子,让我们添加由每个箱子的标准偏差给出的误差条:

^{pr2}$

enter image description here

您可以基于numpy.median()创建一个函数,该函数将计算给定间隔的中值:

import numpy as np

def medians(x, y, intervals):
    out = []
    for xmin, xmax in intervals:
        mask = (x >= xmin) & (x < xmax)
        out.append(np.median(y[mask]))
    return np.array(out)

然后将此函数用于所需的时间间隔:

^{pr2}$

相关问题 更多 >