【问题标题】:Seaborn: how to draw a vertical line that matches a specific y value in a cumulative KDE?Seaborn:如何在累积的 KDE 中绘制与特定 y 值匹配的垂直线?
【发布时间】:2020-07-20 21:25:58
【问题描述】:

我正在使用 Seaborn 绘制累积分布,它是使用此代码的 KDE:

sns.distplot(values, bins=20, 
             hist_kws= {'cumulative': True}, 
             kde_kws= {'cumulative': True} )

这给了我以下图表:

我想绘制一条垂直线和相应的 x 索引,其中 y 为 0.8。比如:

如何获得特定 y 的 x 值?

【问题讨论】:

    标签: matplotlib seaborn distribution


    【解决方案1】:

    您可以在 80% 分位数处画一条垂直线:

    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    values = np.random.normal(1, 20, 1000)
    sns.distplot(values, bins=20,
                 hist_kws= {'cumulative': True},
                 kde_kws= {'cumulative': True} )
    plt.axvline(np.quantile(values, 0.8), color='r')
    plt.show()
    

    【讨论】:

    • 漂亮而清晰的解决方案。您可以使用标签注释该行:line = ax.axvline(x, color='r') ax.annotate(f'{x:.0f}', xy=(x,0), xytext=(0,-14), color=line.get_color(), xycoords = ax.get_xaxis_transform(), textcoords="offset points", size=12, ha="center")
    【解决方案2】:

    answer by @JohanC 可能是最好的。我走了另一条路,这可能是一个更通用的解决方案。

    思路是先得到kde线的坐标,然后求出越过阈值的点的索引

    values = np.random.normal(size=(100,))
    fig = plt.figure()
    ax = sns.distplot(values, bins=20, 
                 hist_kws= {'cumulative': True}, 
                 kde_kws= {'cumulative': True} )
    
    x,y = ax.lines[0].get_data()
    thresh = 0.8
    idx = np.where(np.diff(np.sign(y-thresh)))[0]
    x_val = x[idx[0]]
    ax.axvline(x_val, color='red')
    

    【讨论】:

    • 答案可以进一步改进以找到精确的插值 x 值,如this magic post
    • 我选择@JohanC 答案是因为它更简单,但这个答案也很棒。这个可以更有效,因为没有必要重新处理直方图。我还喜欢它提供了一个插值而不是人口中存在的值。
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 2019-06-11
    • 2013-05-20
    • 2019-02-02
    相关资源
    最近更新 更多