如何将一条垂直线添加到它选择的 seaborn dist 图中? [英] How can I add a vertical line to a seaborn dist plot where it picks?

查看:41
本文介绍了如何将一条垂直线添加到它选择的 seaborn dist 图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在seaborn dist图中y在其最大值的x位置添加一条垂直线?

How can I add a vertical line at the x-location in which y is on its maximum in a seaborn dist plot?

import seaborn as sns, numpy as np
sns.set(); np.random.seed(0)
x = np.random.randn(5000)
ax = sns.distplot(x, kde = False)

PS_ 在上面的示例中,我们知道它可能会选择 0.我很想知道对于x的任何给定分布,我通常如何找到该值.

PS_ In the example above, we know that it's probably going to pick at 0. I am interested to know how I can find this value in general, for any given distribution of x.

推荐答案

这是获得更准确点的一种方法.首先得到平滑分布函数,用它来提取最大值,然后去除它.

This is one way to get a more accurate point. First get the smooth distribution function, use it to extract the maxima, and then remove it.

import seaborn as sns, numpy as np
import matplotlib.pyplot as plt
sns.set(); np.random.seed(0)
x = np.random.randn(5000)
ax = sns.distplot(x, kde = True)

x = ax.lines[0].get_xdata()
y = ax.lines[0].get_ydata()
plt.axvline(x[np.argmax(y)], color='red')
ax.lines[0].remove()

编辑替代解决方案,无需使用 kde = True

Edit Alternate solution without using kde=True

import seaborn as sns, numpy as np
from scipy import stats
import matplotlib.pyplot as plt

sns.set(); np.random.seed(0)
x = np.random.randn(5000)
ax = sns.distplot(x, kde = False)

kde = stats.gaussian_kde(x) # Compute the Gaussian KDE
idx = np.argmax(kde.pdf(x)) # Get the index of the maximum
plt.axvline(x[idx], color='red') # Plot a vertical line at corresponding x

这导致实际分布而不是密度值

This results in the actual distribution and not the density values

这篇关于如何将一条垂直线添加到它选择的 seaborn dist 图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆