我试图从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绘制它,它给了我这个图:
现在我想通过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
我的问题是:给定一个数据帧和所示的kdeplot,我如何得到这个图中某个点x的概率
编辑:将代码添加到绘图sns.kdeplot
为什么带有
sklearn
的绘图看起来不同?因为默认情况下带宽设置为1。从你的x-数据来看应该更高。您只需更改一行即可解决此问题:现在,Seaborn实际上自动设置了带宽,Scipy允许您按照explained here的方式进行设置
Seaborn是matplotlib顶部的一个层,它返回matplotlib轴,因此您可以使用this question关于从matplotlib绘图获取数据的相同答案
此文件的输出看起来与您想要的一样:
相关问题 更多 >
编程相关推荐