【问题标题】:Get data points from Seaborn distplot从 Seaborn distplot 获取数据点
【发布时间】:2021-05-24 18:23:08
【问题描述】:

我用

sns.distplot 

绘制观察的单变量分布。不过,我不仅需要图表,还需要数据点。如何从 matplotlib 轴(由 distplot 返回)获取数据点?

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您可以使用matplotlib.patches API。例如,要获取第一行:

    sns.distplot(x).get_lines()[0].get_data()
    

    这将返回两个包含行的 x 和 y 值的 numpy 数组。

    对于柱状图,信息存储在:

    sns.distplot(x).patches
    

    您可以通过函数patches.get_height()获取条形高度:

    [h.get_height() for h in sns.distplot(x).patches]
    

    【讨论】:

    • 这并不完全可靠。如果在调用distplot 之前Axes 上有任何行,您将从该行获取数据。
    • 另一个提示:获取 bin 左边缘、宽度和高度:l = [[h.xy[0], h.get_width(), h.get_height()] for h in sns.distplot(x).patches]
    • 我刚刚测试了解决方案,但它对我不起作用,因为“get_lines()”不是 FacetGrid 对象的有效方法。我已经成功使用了这个答案:stackoverflow.com/questions/46248348/…
    【解决方案2】:

    如果您想获取直方图的 kde 值,可以使用 scikit-learn KernelDensity 函数:

    import numpy as np
    import pandas as pd
    from sklearn.neighbors import KernelDensity
    
    ds=pd.read_csv('data-to-plot.csv')
    X=ds.loc[:,'Money-Spent'].values[:, np.newaxis]
    
    
    kde = KernelDensity(kernel='gaussian', bandwidth=0.75).fit(X) #you can supply a bandwidth
                                                                  #parameter. 
    
    x=np.linspace(0,5,100)[:, np.newaxis]
    
    log_density_values=kde.score_samples(x)
    density=np.exp(log_density)
    
    array([1.88878660e-05, 2.04872903e-05, 2.21864649e-05, 2.39885206e-05,
           2.58965064e-05, 2.79134003e-05, 3.00421245e-05, 3.22855645e-05,
           3.46465903e-05, 3.71280791e-05, 3.97329392e-05, 4.24641320e-05,
           4.53246933e-05, 4.83177514e-05, 5.14465430e-05, 5.47144252e-05,
           5.81248850e-05, 6.16815472e-05, 6.53881807e-05, 6.92487062e-05,
           7.32672057e-05, 7.74479375e-05, 8.17953578e-05, 8.63141507e-05,
           ..........................
           ..........................
           3.93779919e-03, 4.15788216e-03, 4.38513011e-03, 4.61925890e-03,
           4.85992626e-03, 5.10672757e-03, 5.35919187e-03, 5.61677855e-03])
    

    【讨论】:

    • 可能是density=np.exp(log_density_values) 而不是density=np.exp(log_density)
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2020-06-16
    • 2019-08-03
    • 2021-11-26
    • 2015-10-22
    相关资源
    最近更新 更多