How can I add a vertical line to a seaborn dist pl

2019-08-23 11:13发布

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_ 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.

1条回答
Animai°情兽
2楼-- · 2019-08-23 11:22

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()

enter image description here

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

enter image description here

查看更多
登录 后发表回答