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

如何修复Pandas绘图中X轴未显示Team索引的问题?

解决pandas绘图X轴显示数字而非球队名称的问题

我有一份包含球队、击球(Ba)和投球(Bo)数据的表格,执行以下代码绘制柱状图时,X轴显示的是数字而非球队名称:

bat_bowl = table[['Team','Ba','Bo']]
bat_bowl.set_index('Team')

ax = bat_bowl.plot.bar(rot=25)
plt.title('Comparison of Batting and Bowling by Teams')
plt.xlabel('Teams')

问题原因

bat_bowl.set_index('Team')默认返回一个设置好索引的新DataFrame,但你没有将这个新对象赋值回bat_bowl,导致后续绘图仍使用原始的、带有数字默认索引的DataFrame,因此X轴显示数字而非球队名称。

解决方案

提供三种可行的修正方式:

方式1:赋值回原变量

将设置索引后的新DataFrame重新赋值给bat_bowl,确保后续绘图使用带球队索引的数据:

bat_bowl = table[['Team','Ba','Bo']]
bat_bowl = bat_bowl.set_index('Team')

ax = bat_bowl.plot.bar(rot=25)
plt.title('各队击球与投球数据对比')
plt.xlabel('球队')
plt.show()

方式2:使用inplace=True直接修改原DataFrame

通过inplace=True参数直接在原DataFrame上修改索引,无需重新赋值:

bat_bowl = table[['Team','Ba','Bo']]
bat_bowl.set_index('Team', inplace=True)

ax = bat_bowl.plot.bar(rot=25)
plt.title('各队击球与投球数据对比')
plt.xlabel('球队')
plt.show()

方式3:绘图时直接指定X轴列

无需修改索引,在plot.bar()中通过x='Team'指定X轴使用球队列数据:

bat_bowl = table[['Team','Ba','Bo']]

ax = bat_bowl.plot.bar(x='Team', rot=25)
plt.title('各队击球与投球数据对比')
plt.xlabel('球队')
plt.show()

以上任意一种方式都能让柱状图的X轴显示对应的球队名称。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:32:08