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

如何修复使用pandas、matplotlib、seaborn绘制图表时的TypeError?

解决Seaborn countplot的TypeError问题

问题代码

df_train = pd.read_csv('../content/train.csv')
df_test = pd.read_csv('../content/test.csv')
df_submission = pd.read_csv('../content/sample_submission.csv')

f, ax = plt.subplots(1, 2, figsize=(18, 8))

df_train[['Sex', 'Survived']].groupby(['Sex'], as_index=True).mean().plot.bar(ax=ax[0])
ax[0].set_title('Survived vs Sex')

sns.countplot('Sex', hue='Survived', data=df_train, ax=ax[1])
ax[1].set_title('Sex: Survived vs Dead')

plt.show()

报错信息

TypeError                                 Traceback (most recent call last)
<ipython-input-39-38b53be3f652> in <cell line: 6>()
      4 ax[0].set_title('Survived vs Sex')
      5 
----> 6 sns.countplot('Sex', hue='Survived', data=df_train, ax=ax[1])
      7 ax[1].set_title('Sex: Survived vs Dead')
      8 

TypeError: countplot() got multiple values for argument 'data'

错误原因

新版本Seaborn(>=0.11.0)调整了countplot的参数规则,不再支持将x轴变量作为位置参数传递。直接写'Sex'会被识别为data参数的位置输入,和后面显式指定的data=df_train冲突,触发"multiple values for argument 'data'"错误。

修复方案

显式指定x=参数,将'Sex'赋值给x字段:

修改后的关键代码行:

sns.countplot(x='Sex', hue='Survived', data=df_train, ax=ax[1])

完整修复后代码

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

df_train = pd.read_csv('../content/train.csv')
df_test = pd.read_csv('../content/test.csv')
df_submission = pd.read_csv('../content/sample_submission.csv')

f, ax = plt.subplots(1, 2, figsize=(18, 8))

df_train[['Sex', 'Survived']].groupby(['Sex'], as_index=True).mean().plot.bar(ax=ax[0])
ax[0].set_title('Survived vs Sex')

# 修复countplot的参数传递方式
sns.countplot(x='Sex', hue='Survived', data=df_train, ax=ax[1])
ax[1].set_title('Sex: Survived vs Dead')

plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 10:11:21