如何在(seaborn)KDE图中定位中值?

2024-05-16 20:51:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着和肖伯恩做一个Kernel Density Estimation (KDE) plot定位中间带。代码如下所示:

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

sns.set_palette("hls", 1)
data = np.random.randn(30)
sns.kdeplot(data, shade=True)

# x_median, y_median = magic_function()
# plt.vlines(x_median, 0, y_median)

plt.show()

如您所见,我需要一个magic_function()来从kdeplot中获取x和y的中值。然后我想用例如vlines来绘制它们。但是,我不知道怎么做。结果应该是这样的(显然这里的黑色中间条是错误的):

enter image description here

我想我的问题和肖伯恩没有严格的关系,也适用于其他类型的matplotlib情节。任何想法都是非常感激的。


Tags: importdatamatplotlibasmagicnpfunctionplt
1条回答
网友
1楼 · 发布于 2024-05-16 20:51:38

你需要:

  1. 提取kde行的数据
  2. 积分计算累积分布函数(CDF)
  3. 找出使CDF等于1/2的值,即中值
import numpy as np
import scipy
import seaborn as sns
import matplotlib.pyplot as plt

sns.set_palette("hls", 1)
data = np.random.randn(30)
p=sns.kdeplot(data, shade=True)

x,y = p.get_lines()[0].get_data()

#care with the order, it is first y
#initial fills a 0 so the result has same length than x
cdf = scipy.integrate.cumtrapz(y, x, initial=0)

nearest_05 = np.abs(cdf-0.5).argmin()

x_median = x[nearest_05]
y_median = y[nearest_05]

plt.vlines(x_median, 0, y_median)
plt.show()

Result

相关问题 更多 >