2015-12-18 76 views
3

我希望能够从使用Python的Seaborn生成的核心密度图中提取特征参数。关于获得分布的中位数有一个很好的example,我想看看这是否可以推广为一维数据的多模分布,特别是在2D情况下。从seaborn kdeplots中提取特征参数

下面是一个最小的例子,我从中手动推导出1D情况下每个峰的值。我希望通过可用的对象找到更系统化,更适用于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) 
+2

我鼓励你直接使用statsmodels KDE对象。这将比试图从等值线图中获取信息要简单得多,最终更加强大。 – mwaskom

回答

1

您可以通过下面的代码获取的路径:

ax = sns.kdeplot(data.x, data.y, shade=True) 

for path in ax.collections[-1].get_paths(): 
    x, y = path.vertices.mean(axis=0) 
    ax.plot(x, y, "ro") 

这里是输出:

enter image description here

ax.collections是对应于每一个水平PathCollection对象的列表Axes对象。

每个PathCollection包含一个Path对象的列表,你可以通过get_paths()方法获得。

路径的点保存在vertices数组中。

如果你想获得更多的信息,你需要得到的Axes.contourf返回的对象,第一个补丁的方法contourf()

from matplotlib.axes import Axes 

def contourf(self, *args, **kw): 
    self._quadcontourset = self.old_contourf(*args, **kw) 
    return self._quadcontourset 

Axes.old_contourf = Axes.contourf 
Axes.contourf = contourf 

然后你就可以通过ax._quadcontourset得到QuadContourSet对象。请阅读QuadContourSet的源代码以了解如何使用它。