How can I add a vertical line to a seaborn dist plot where it picks?

China☆狼群 提交于 2019-12-24 21:23:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!