如何调整Seaborn displot中KDE图的带宽?解决参数报错问题
解决Seaborn displot KDE图的带宽调整与负值问题
1. 正确调整带宽的方法
你收到警告是因为displot作为Figure级别的函数,不支持kde_kws参数。对于kind='kde'的displot,直接将bw_adjust作为参数传入即可:
sns.displot(df, x='duration', y='distance', kind='kde', fill=True, bw_adjust=0.5)
如果需要传递更多KDE相关参数(比如bw_method),直接在displot中添加对应参数即可,无需嵌套在kde_kws里。
2. 消除duration无意义负值的方案
除了调整带宽,更直接的方式是通过clip参数限制KDE的取值范围——因为duration不可能为负,可给x轴设置裁剪范围:
sns.displot(df, x='duration', y='distance', kind='kde', fill=True, bw_adjust=0.5, clip=(0, None))
这样KDE曲线会被限制在x>0的区域,不会出现无意义的负值。
另外,也可以先预处理数据,过滤掉duration为负的异常值(如果数据中存在这类值)再绘图:
filtered_df = df[df['duration'] > 0] sns.displot(filtered_df, x='duration', y='distance', kind='kde', fill=True, bw_adjust=0.5)
内容的提问来源于stack exchange,提问作者fenaux
相关产品推荐
相关产品推荐

