我希望能够从使用 Python 的 Seaborn 生成的核密度图中提取特征参数。虽然有一个非常好的example https://stackoverflow.com/questions/28956622/how-to-locate-the-median-in-a-seaborn-kde-plot在获得分布的中位数时,我想看看这是否可以推广到一维数据的多模态分布,特别是在二维情况下。
下面是一个最小的示例,我从中手动导出一维情况下每个峰值的值。我希望使用可用的对象找到更系统且适用于 2D 的东西。
import numpy as np
import scipy
import pandas as pd
import seaborn as sns
sns.set(style="white", color_codes=True, font_scale=2)
x1 = np.random.normal(-1.5,1,1000)
y1 = np.random.normal(1.5,1,1000)
x2 = np.random.normal(1.5,1,1000)
y2 = np.random.normal(-1.5,1,1000)
x = np.concatenate((x1,x2))
y = np.concatenate((y1,y2))
d = {'x': pd.Series(x), 'y': pd.Series(y)}
data = pd.DataFrame(d)
px = sns.kdeplot(data.x, shade=True)
x,y = px.get_lines()[0].get_data()
xysel = np.array([(x,y) for x,y in zip(x,y) if x < 0])
imax = np.argmax(xysel[:,1])
x_median = xysel[imax,0]
y_median = xysel[imax,1]
plt.vlines(x_median, 0, y_median, linestyles='dashed', color='b')
px.set_xlim(-5,5)
plt.show()
py = sns.kdeplot(data.y, shade=True, color='r')
x,y = py.get_lines()[0].get_data()
xysel = np.array([(x,y) for x,y in zip(x,y) if x > 0])
imax = np.argmax(xysel[:,1])
x_median = xysel[imax,0]
y_median = xysel[imax,1]
plt.vlines(x_median, 0, y_median, linestyles='dashed', color='r')
py.set_xlim(-5,5)
plt.show()
p = sns.kdeplot(data.x, data.y, shade=True)