获取点以创建KDE绘图

2024-04-20 09:49:48 发布

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

我试图从KDE绘图中获取点,以便通过API发送点,这样绘图就可以通过前端显示。例如,如果我有以下数据:

df = pd.DataFrame({'x': [3000.0,
  2897.0,
  4100.0,
  2539.28,
  5000.0,
  3615.0,
  2562.05,
  2535.0,
  2413.0,
  2246.0],
 'y': [1, 2, 1, 1, 1, 2, 1, 3, 1, 1]})
import seaborn as sns

sns.kdeplot(x=df['x'], weights=df['y'])

我用seaborn kdeplot绘制它,它给了我这个图:

seaborn kdeplot

现在我想通过API发送这个图的一些点。我的想法是使用sklearn的KernelDensity来估计某些点的密度。所以我用了这个代码:

from sklearn.neighbors import KernelDensity
x_points = np.linspace(0, df['x'].max(), 30)
kde = KernelDensity()
kde.fit(df['x'].values.reshape(-1, 1), sample_weight=df['y'])
 
logprob = kde.score_samples(x_points.reshape(-1, 1))
 
new_df = pd.DataFrame({'x': x_points, 'y': np.exp(logprob)})

如果我用线图绘制,它看起来一点也不像seaborn kdeplot

Lineplot with points from sklearn KernelDensity

我的问题是:给定一个数据帧和所示的kdeplot,我如何得到这个图中某个点x的概率

编辑:将代码添加到绘图sns.kdeplot


Tags: 数据importapi绘图dataframedf绘制sklearn
1条回答
网友
1楼 · 发布于 2024-04-20 09:49:48

为什么带有sklearn的绘图看起来不同?因为默认情况下带宽设置为1。从你的x-数据来看应该更高。您只需更改一行即可解决此问题:

kde = KernelDensity(bandwidth=500)

现在,Seaborn实际上自动设置了带宽,Scipy允许您按照explained here的方式进行设置

Seaborn是matplotlib顶部的一个层,它返回matplotlib轴,因此您可以使用this question关于从matplotlib绘图获取数据的相同答案

import matplotlib.pyplot as plt
plt.gca().get_lines()[0].get_xydata()

此文件的输出看起来与您想要的一样:

array([[5.70706380e+02, 7.39051159e-07],
       [6.01382697e+02, 9.00695337e-07],
       [6.32059015e+02, 1.09427429e-06],
       [6.62735333e+02, 1.32531892e-06],
       [6.93411651e+02, 1.60015322e-06],
       [7.24087969e+02, 1.92597554e-06],
       [7.54764286e+02, 2.31094202e-06],
       [7.85440604e+02, 2.76425104e-06],
       [8.16116922e+02, 3.29622720e-06],
       ...])

相关问题 更多 >