使用Seaborn pointplot触发TypeError:意外关键字参数‘alpha’
解决seaborn pointplot()不支持alpha参数的问题
问题场景
运行分析美国县失业率的Python代码时,调用sns.pointplot()传入alpha=0.8参数触发TypeError,提示函数不接受该关键字参数。
原代码
import kagglehub # Download latest version path = kagglehub.dataset_download("jayrav13/unemployment-by-county-us") import pandas as pd df = pd.read_csv(path) print(df) import numpy as np import seaborn as sns import matplotlib.pyplot as plt #Let us check for the county with the highest unemployment rate Exp = df.groupby('Rate').max() Exp #Getting rows of San Juan County Colorado only c = df.loc[(df['County']=='San Juan County') & (df['State']=='Colorado')] #print(c) #Plotting San Juan unemployment rate around the years surrounding 1990s Recession fig, (ax1, ax2, ax3) = plt.subplots(1, 3,figsize=(30,8)) group = c.loc[c['Year']==1990] sns.pointplot(group['Month'], group['Rate'], alpha=0.8, ax=ax1) plt.show()
报错日志
Traceback (most recent call last): File ".\unEmploymentRate_kaggle.py", line 46, in <module> sns.pointplot(group['Month'], group['Rate'], alpha=0.8, ax=ax1) TypeError: pointplot() got an unexpected keyword argument 'alpha'
解决方案
seaborn的pointplot()本身没有alpha参数,要设置点或线的透明度,需通过scatter_kws(控制点样式)或line_kws(控制线样式)参数,把透明度设置传递给底层的matplotlib元素。同时新版本seaborn推荐用data参数传入DataFrame,指定x/y列名的写法,更符合API规范:
修改后的代码行:
sns.pointplot(data=group, x='Month', y='Rate', scatter_kws={'alpha': 0.8}, ax=ax1)
如果需要同时设置线的透明度,可添加line_kws:
sns.pointplot(data=group, x='Month', y='Rate', scatter_kws={'alpha': 0.8}, line_kws={'alpha': 0.8}, ax=ax1)
内容的提问来源于stack exchange,提问作者Vineet Tripathi
相关产品推荐
相关产品推荐

