gpt4 book ai didi

python - 如何在seaborn distplot 中添加一条垂直线?

转载 作者:行者123 更新时间:2023-12-02 03:14:26 35 4
gpt4 key购买 nike

如何在 Seaborn 分布图中 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)

PS_ 在上面的示例中,我们知道它可能会选择 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()

enter image description here

编辑不使用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

这会产生实际分布,而不是密度值

enter image description here

关于python - 如何在seaborn distplot 中添加一条垂直线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56600828/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com