问题
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:
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()
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
来源:https://stackoverflow.com/questions/56600828/how-can-i-add-a-vertical-line-to-a-seaborn-dist-plot-where-it-picks