Seaborn:如何在累积KDE中绘制与特定y值匹配的垂直线?

时间:2020-07-20 13:01:35

标签: matplotlib seaborn distribution

我正在使用Seaborn绘制累积分布,并且使用以下代码是KDE:

$coDoc->getErrorMessage()

这给了我以下图表:

Cumulative distribution and kde

我想画一条垂直线和相应的x索引,其中y为0.8。像这样:

KDE with vertical line

如何获取特定y的x值?

2 个答案:

答案 0 :(得分:2)

您可以在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()

example plot

答案 1 :(得分: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')

enter image description here