You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

seaborn barplot报错:TypeError:仅接受0-1个位置参数却传入2个

词频柱状图绘制报错:TypeError 问题解决

问题场景

执行完以下文本预处理代码后:

# 提取所有单词的词根
stemmer = SnowballStemmer(language='english')
stem=[]
for word in lines:
    stem.append(stemmer.stem(word))
stem[:20]
# 移除停用词(句子中极常见的无意义词汇)
stem2 = []
for word in stem:
    if word not in nlp.Defaults.stop_words:
        stem2.append(word)
# 创建词根的新DataFrame并展示高频词统计
df = pd.DataFrame(stem2)
df=df[0].value_counts()
df # 展示新的统计结果

运行词频柱状图绘制代码时出现错误:

# 绘制Top20高频词柱状图
df = df[:20]
plt.figure(figsize=(10,5))
sns.barplot(df.values, df.index, alpha=0.8)
plt.title('Top Words Overall')
plt.xlabel('Count of words', fontsize=12)
plt.ylabel('Word from Tweet', fontsize=12)
plt.show()

报错信息:

TypeError                                 Traceback (most recent call last)
<ipython-input-20-3371fa9e7860> in <module>
      2 df = df[:20]
      3 plt.figure(figsize=(10,5))
----> 4 sns.barplot(df.values, df.index, alpha=0.8)
      5 plt.title('Top Words Overall')
      6 plt.xlabel('Count of words', fontsize=12)

TypeError: barplot() takes from 0 to 1 positional arguments but 2 were given
<Figure size 720x360 with 0 Axes>

问题原因

新版本Seaborn的barplot()函数已取消位置参数传递支持,不能直接将数据作为无关键字的参数传入,必须通过显式的关键字参数指定x和y对应的数据。

解决方法

将barplot的调用改为关键字参数形式,以下几种写法均可:

写法1:直接指定x、y对应的数据

plt.figure(figsize=(10,5))
sns.barplot(x=df.values, y=df.index, alpha=0.8)
plt.title('Top Words Overall')
plt.xlabel('Count of words', fontsize=12)
plt.ylabel('Word from Tweet', fontsize=12)
plt.show()

写法2:利用Pandas Series属性直接传入

plt.figure(figsize=(10,5))
sns.barplot(x=df, y=df.index, alpha=0.8)
plt.title('Top Words Overall')
plt.xlabel('Count of words', fontsize=12)
plt.ylabel('Word from Tweet', fontsize=12)
plt.show()

写法3:转换为DataFrame后传入(可读性更强)

df_top20 = df[:20].reset_index()
df_top20.columns = ['Word', 'Count']

plt.figure(figsize=(10,5))
sns.barplot(x='Count', y='Word', data=df_top20, alpha=0.8)
plt.title('Top Words Overall')
plt.xlabel('Count of words', fontsize=12)
plt.ylabel('Word from Tweet', fontsize=12)
plt.show()

内容的提问来源于stack exchange,提问作者Yudi Darmawan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 22:42:30