从seaborn kdeplot Level(2D)python中提取数据

2024-09-27 19:31:29 发布

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

当kdeplot的输入为2D时,是否可以从其获取数据? 我有以下资料:

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),它返回一个<AxesSubplot:>对象,我不知道如何解压缩它的信息,因为kde.lines[0]然后返回list index out of range
我需要计算每个绘制轮廓轴上的最大值和最小值(分别)作为每个变量的离散度


Tags: fromimportnumpy信息asnplinela
2条回答

在本例中,可以从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)]

enter image description here

感谢r初学者提供的解决方案,它确实解决了问题。我只是在访问数据[0]以获取“顶点”值时遇到了一些问题,因为它是一个路径对象,我不熟悉这些对象。 但根据您的回答,我认为(针对我的特定问题)使用以下方法可能更简单:

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()

相关问题 更多 >

    热门问题