如何在(季节性的)KDE图中找到中位数?
我正在尝试对seaborn进行内核密度估计(KDE)绘图并找到中位数。代码看起来像这样:
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()
从中获取x和y的中值kdeplot
。然后我想用例如来绘制它们vlines
。但是,我不知道该怎么做。结果应该看起来像这样(显然黑色中间条在这里是错误的):
我想我的问题与seaborn并不严格相关,也适用于其他种类的matplotlib图。任何想法都将不胜感激。
-
你需要:
- 提取kde行的数据
- 对其进行积分以计算累积分布函数(CDF)
-
找到使CDF等于1/2的值,即中位数
import numpy as np
import scipy
import seaborn as sns
import matplotlib.pyplot as pltsns.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()