如何将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
相关产品推荐
相关产品推荐

