从seaborn kdeplots中提取特征参数

2024-10-01 11:22:38 发布

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

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

下面是一个最小的例子,我从中手动推导出1D情况下每个峰值的值。我希望能找到更适用于二维和系统化的对象。在

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)

Tags: importtruedatagetasnppltrandom
1条回答
网友
1楼 · 发布于 2024-10-01 11:22:38

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

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是对应于axis对象中每个级别的PathCollection对象的列表。在

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

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

如果要获取更多信息,需要获取Axes.contourf的返回对象,首先修补contourf()方法:

^{pr2}$

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

相关问题 更多 >