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

pandas.pivot转换后,Seaborn绘制柱状图无法识别x轴year的问题求助

解决方案:Seaborn无法识别year字段的问题

问题核心在于year是df3的索引而非普通列,Seaborn的barplot默认从DataFrame的列中查找x参数指定的字段,因此会抛出无法识别的错误。

以下是两种直接可行的解决方法:

方法1:重置索引,将year转为普通列

先执行重置索引操作,把year从索引转换为常规列:

df3 = df3.reset_index()

之后再运行你的绘图代码即可:

sns.barplot(data=df3, x='year', y="Total in Practice")

方法2:直接使用索引作为x轴

如果不想修改DataFrame结构,可以直接将索引传给x参数:

sns.barplot(data=df3, x=df3.index, y="Total in Practice")

若需要将x轴标签改为"year",可手动设置:

import matplotlib.pyplot as plt
ax = sns.barplot(data=df3, x=df3.index, y="Total in Practice")
ax.set_xlabel('year')
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 20:10:36