从 seaborn kdeplot 级别提取数据 (2D) python

extracting data from seaborn kdeplot levels (2D) python

输入为二维时是否可以从 kdeplot 获取数据? 我有以下内容:

import numpy as np    
from seaborn import kdeplot

lA = np.randon.normal(1,0.2,1000)
ld = np.randon.normal(1,0.2,1000)
kde = kdeplot(x=lA,y=ld)

如果这只是 1D,我可以通过以下方式获取信息:

lA = np.randon.normal(1,0.2,1000)
kde = kdeplot(lA)
line = kde.lines[0]
x, y = line.get_data()

但作为输入是 2D (lA, ld) ,它 returns 一个 <AxesSubplot:> 对象,我不知道如何解压它的信息,因为 kde.lines[0] 然后 returns list index out of range.
我需要计算每个绘制轮廓轴的最大值和最小值(分别)作为我对每个变量的分散。

您可以从 LineCollection 对象中获取图中绘制的路径。

import numpy as np    
from seaborn import kdeplot
import random
from matplotlib.collections import LineCollection

lA = np.random.normal(1,0.2,1000)
ld = np.random.normal(1,0.2,1000)
kde = kdeplot(x=lA,y=ld)

data = []
for i in kde.get_children():
    if i.__class__.__name__ == 'LineCollection':
        data.append(i.get_paths())

kde.get_children()
[<matplotlib.collections.LineCollection at 0x28fb3ec2fd0>,
 <matplotlib.collections.LineCollection at 0x28fb3ed5320>,
 <matplotlib.collections.LineCollection at 0x28fb3ed55f8>,
 <matplotlib.collections.LineCollection at 0x28fb3ed58d0>,
 <matplotlib.collections.LineCollection at 0x28fb3ed5ba8>,
 <matplotlib.collections.LineCollection at 0x28fb3ed5e80>,
 <matplotlib.collections.LineCollection at 0x28fb3ee1198>,
 <matplotlib.collections.LineCollection at 0x28fb3ee1470>,
 <matplotlib.collections.LineCollection at 0x28fb3ee1748>,
 <matplotlib.collections.LineCollection at 0x28fb3ee1a20>,
 <matplotlib.spines.Spine at 0x28fb0cd3898>,
 <matplotlib.spines.Spine at 0x28fb0cd3978>,
 <matplotlib.spines.Spine at 0x28fb0cd3a58>,
 <matplotlib.spines.Spine at 0x28fb0cd3b38>,
 <matplotlib.axis.XAxis at 0x28fb0cd3828>,
 <matplotlib.axis.YAxis at 0x28fb0cd3eb8>,
 Text(0.5, 1.0, ''),
 Text(0.0, 1.0, ''),
 Text(1.0, 1.0, ''),
 <matplotlib.patches.Rectangle at 0x28fb3eb9630>]

data[0]
[Path(array([[1.0194036 , 0.43072548],
        [1.02780525, 0.42839334],
        [1.0362069 , 0.4265304 ],
        ...,
        [1.01100196, 0.43337965],
        [1.01752133, 0.43134949],
        [1.0194036 , 0.43072548]]), None)]

感谢r-beginners的解答,确实解决了问题。我只是在访问 data[0] 以获取 'vertices' 值时遇到了一些麻烦,因为它是一个 Path 对象,我不熟悉这些。 但是根据您的回答,我认为使用它可能更直接(对于我的特定问题):

import matplotlib.pyplot as plt
from seaborn import kdeplot
from matplotlib import collections
import numpy as np

lA = np.random.normal(1, 0.2, 1000)
ld = np.random.normal(1, 0.2, 1000)
kde = kdeplot(x=lA, y=ld, levels=[0.3173]) # to get 1-sigma equivalent level

# Here I get the vertices information for each axis
p = kde.collections[0].get_paths()[0]
v = p.vertices
lx = [v[r][0] for r in range(len(v))]
ly = [v[r][1] for r in range(len(v))]

# Then I plot the horizontal limits of lx
plt.axvline(min(lx), c='r')
plt.axvline(max(lx), c='r')
plt.show()