如何修复Seaborn KDE绘制地理坐标时的TypeError错误
解决Seaborn 0.12.0中kdeplot的TypeError问题
问题背景
我有一个包含2000行经纬度数据的DataFrame:
Latitude Longitude 31.400091 -109.782830 31.400091 -108.782830 31.410091 -108.782830 31.405091 -109.782830 31.400091 -110.77830 31.460091 -12.782830 ... ...
尝试用Seaborn的KDE绘制点密度,代码如下:
x = df['Longitude'] y = df['Latitude'] x = x.to_numpy() y = y.to_numpy() sns.kdeplot(x, y, zorder=0, n_levels=6, shade=True, cbar=True, shade_lowest=False, cmap='viridis')
运行后触发错误:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [58], in <cell line: 1>() ----> 1 sns.kdeplot(x, y, zorder=0, n_levels=6, shade=True, 2 cbar=True, shade_lowest=False, cmap='viridis') TypeError: kdeplot() takes from 0 to 1 positional arguments but 2 positional arguments (and 1 keyword-only argument) were given
试过转numpy数组和直接用Series,结果一致,Seaborn版本为0.12.0。
原因分析
Seaborn从0.11版本开始重构了kdeplot的参数逻辑,不再支持直接传入两个位置参数x和y,必须通过关键字参数传递,或者结合data参数绑定DataFrame来指定列。
解决方案
有两种可行的修正方式:
方式1:显式指定x、y关键字参数
直接给kdeplot传入命名参数,无需转换为numpy数组(Series或数组格式都支持):
sns.kdeplot( x=df['Longitude'], y=df['Latitude'], zorder=0, n_levels=6, shade=True, cbar=True, shade_lowest=False, cmap='viridis' )
方式2:使用data参数绑定DataFrame
通过data参数指定数据源,再传入列名字符串,代码更简洁:
sns.kdeplot( data=df, x='Longitude', y='Latitude', zorder=0, n_levels=6, shade=True, cbar=True, shade_lowest=False, cmap='viridis' )
额外提示
Seaborn 0.12.0中shade参数已被标记为废弃,建议改用fill参数以兼容后续版本:
sns.kdeplot( data=df, x='Longitude', y='Latitude', zorder=0, n_levels=6, fill=True, # 替代原shade参数 cbar=True, shade_lowest=False, cmap='viridis' )
内容的提问来源于stack exchange,提问作者JEG
相关产品推荐
相关产品推荐

