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

如何将DataFrame绘图的X轴设置为State列而非索引值

解决X轴显示州名称的方法

当前你的数据框里State是普通列,df.plot()默认用索引作为X轴,所以看不到州名。可以用以下两种方法解决:

方法一:将State设为数据框索引

修改代码如下:

print(df.info())
print(df)
# 将State列设置为索引
df.set_index('State', inplace=True)
df.plot(kind='bar')
plt.xlabel('State')
plt.ylabel('Total Sales')
plt.title('Total Sales by State')
plt.show()

方法二:绘图时指定x和y参数

不需要修改索引,直接在plot函数里指定X轴和Y轴对应的列:

print(df.info())
print(df)
df.plot(kind='bar', x='State', y='SumOfTotalPrice')
plt.xlabel('State')
plt.ylabel('Total Sales')
plt.title('Total Sales by State')
plt.show()

两种方法都能让X轴显示州的缩写名称,替换默认的数字索引。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 05:12:20