Seaborn绘制KDE图报错:hue无法分配宽格式数据及索引重复问题
解决Seaborn displot绘制分组KDE+Rug的报错问题
错误原因分析
- 第一个错误
The following variable cannot be assigned with wide-form data 'hue':未指定x轴变量,Seaborn无法确定针对哪列生成KDE分布,必须显式声明x='IR'。 - 第二个错误
ValueError: cannot reindex on an axis with duplicate labels:DataFrame存在重复索引,导致Seaborn处理rug元素时无法正确对齐数据。
解决方案
方法一:重置DataFrame索引
先消除重复索引标签,再执行绘图代码:
# 重置索引,丢弃旧索引列 df = df.reset_index(drop=True) # 重新绘制分组KDE+Rug import seaborn as sns sns.displot(df, x='IR', kind="kde", hue='type', rug=True)
方法二:手动拆分绘制KDE与Rug
如果重置索引仍无效,可分开绘制KDE曲线和每个分组的rug:
import seaborn as sns import matplotlib.pyplot as plt # 绘制分组KDE g = sns.displot(df, x='IR', kind="kde", hue='type') # 遍历每个type分组,添加对应rug for type_label in df['type'].unique(): group_data = df[df['type'] == type_label] sns.rugplot(data=group_data, x='IR', ax=g.axes[0,0], color=g._palette[type_label]) plt.show()
方法三:使用底层绘图函数组合
直接用kdeplot和rugplot在单个轴上实现:
import seaborn as sns import matplotlib.pyplot as plt plt.figure(figsize=(8, 5)) # 绘制分组KDE曲线 sns.kdeplot(data=df, x='IR', hue='type') # 添加分组rug标记 sns.rugplot(data=df, x='IR', hue='type', height=0.05) plt.show()
内容的提问来源于stack exchange,提问作者Palinuro
相关产品推荐
相关产品推荐

