Rot*_*ail 2 python plot matplotlib seaborn
如何在seaborn dist图中y处于最大值的x位置添加一条垂直线?
import seaborn as sns, numpy as np
sns.set(); np.random.seed(0)
x = np.random.randn(5000)
ax = sns.distplot(x, kde = False)
Run Code Online (Sandbox Code Playgroud)
PS_ 在上面的例子中,我们知道它可能会选择 at 0
。对于任何给定的 x 分布,我很想知道如何找到这个值。
这是获得更准确点的一种方法。首先得到平滑分布函数,用它来提取最大值,然后去除它。
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()
Run Code Online (Sandbox Code Playgroud)
在不使用的情况下编辑替代解决方案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
Run Code Online (Sandbox Code Playgroud)
这导致实际分布而不是密度值