微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从seaborn kdeplot级别2Dpython中提取数据

如何解决从seaborn kdeplot级别2Dpython中提取数据

当 kdeplot 的输入是 2D 时,是否可以从 kdeplot 中获取数据? 我有以下几点:

import numpy as np    
from seaborn import kdeplot

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

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

lA = np.randon.normal(1,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
我需要计算每个绘制轮廓轴的最大值和最小值(单独)作为每个变量的离散度。

解决方法

您可以从 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,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,Text(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

,

感谢初学者的解决方案,它确实解决了问题。我只是在访问 data[0] 以获取“顶点”值时遇到了一些麻烦,因为它是一个 Path 对象,而我不熟悉这些。 但是按照您的回答,我认为使用它可能更直接(对于我的特定问题):

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

lA = np.random.normal(1,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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。