如何从seaborn.kdeplot提取x、y值?调用get_lines()遇索引越界错误
解决seaborn.kdeplot提取数据时的IndexError问题
问题原因
当设置shade=True时,seaborn 0.12.2的kdeplot会生成填充的多边形区域(PolyCollection对象),而非线条对象(Line2D)。你调用的get_lines()方法只能获取线条对象,此时返回空列表,访问[0]自然触发IndexError。
解决方案
根据是否需要保留填充效果,分两种处理方式:
1. 不需要填充效果,只提取线条数据
将shade=True改为shade=False,此时kdeplot会生成线条,原代码即可正常运行:
points = sns.kdeplot(targets, shade=False, label='train').get_lines()[0].get_data() x = points[0] y = points[1]
2. 需要保留填充效果,提取填充区域的顶点数据
如果要保留阴影填充,需从ax.collections中获取多边形对象,再提取其顶点坐标:
import seaborn as sns import matplotlib.pyplot as plt # 绘制带填充的KDE图 ax = sns.kdeplot(targets, shade=True, label='train') # 获取填充的多边形对象 poly_collection = ax.collections[0] # 提取路径顶点数据 path = poly_collection.get_paths()[0] vertices = path.vertices x = vertices[:, 0] # 提取x坐标数组 y = vertices[:, 1] # 提取y坐标数组
内容的提问来源于stack exchange,提问作者James Arten
相关产品推荐
相关产品推荐

