Matplotlib Seaborn:如何在累积KDE中绘制与特定y值匹配的垂直线?
我正在使用Seaborn绘制一个累积分布,它是KDE,使用以下代码:Matplotlib Seaborn:如何在累积KDE中绘制与特定y值匹配的垂直线?,matplotlib,seaborn,distribution,Matplotlib,Seaborn,Distribution,我正在使用Seaborn绘制一个累积分布,它是KDE,使用以下代码: sns.distplot(values, bins=20, hist_kws= {'cumulative': True}, kde_kws= {'cumulative': True} ) 这给了我以下图表: 我想画一条垂直线和相应的x指数,其中y是0.8。比如: 如何获得特定y的x值?您可以在80%分位数处绘制一条垂直线: 导入matplotlib.pyplot作为
sns.distplot(values, bins=20,
hist_kws= {'cumulative': True},
kde_kws= {'cumulative': True} )
这给了我以下图表:
我想画一条垂直线和相应的x指数,其中y是0.8。比如:
如何获得特定y的x值?您可以在80%分位数处绘制一条垂直线:
导入matplotlib.pyplot作为plt
将numpy作为np导入
导入seaborn作为sns
数值=np.随机.正常(1,20,1000)
sns.distplot(值,箱=20,
hist_kws={'cumulative':True},
kde_kws={'cumulative':True})
plt.axvline(np.分位数(值,0.8),color='r')
plt.show()
您可以在80%分位数处绘制一条垂直线:
导入matplotlib.pyplot作为plt
将numpy作为np导入
导入seaborn作为sns
数值=np.随机.正常(1,20,1000)
sns.distplot(值,箱=20,
hist_kws={'cumulative':True},
kde_kws={'cumulative':True})
plt.axvline(np.分位数(值,0.8),color='r')
plt.show()
这可能是最好的。我走了另一条路,这可能是一个更通用的解决方案
其思想是获得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')
这可能是最好的。我走了另一条路,这可能是一个更通用的解决方案
其思想是获得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值,如中所示。我选择@JohanC answer是因为它更简单,但这个答案也很好。因为不需要重新处理柱状图,所以这个方法可能更有效。我还喜欢它给出一个插值,而不是总体中存在的插值。答案可以进一步改进,以找到精确的插值x值,如中所示。我选择@JohanC answer是因为它更简单,但这个答案也很好。因为不需要重新处理柱状图,所以这个方法可能更有效。我还喜欢它给出一个插值,而不是一个存在于总体中的值。很好而且清晰的解决方案。您可以使用以下标签对该行进行注释:
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”)
。您可以使用以下标签注释该行: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”)