如何使用 DataFrame 图 X 轴上的特定列

问题描述 投票:0回答:1

我希望我的绘图在 x 轴上使用状态名称,而不是索引值。 此代码生成图表:

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

这是输出:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 11 entries, 0 to 10
Data columns (total 2 columns):
 #   Column           Non-Null Count  Dtype  
---  ------           --------------  -----  
 0   State            11 non-null     object 
 1   SumOfTotalPrice  11 non-null     float64
dtypes: float64(1), object(1)
memory usage: 304.0+ bytes
None
   State  SumOfTotalPrice
0     AK     1.063432e+07
1     CA     4.172891e+07
2     IL     2.103149e+07
3     IN     2.270681e+08
4     KY     4.144238e+07
5     ME     2.057557e+07
6     MI     4.216375e+07
7     OH     7.970354e+08
8     PA     2.158148e+07
9     SD     1.025623e+07
10    TX     2.061534e+07

该图的 X 轴上没有州名称:

pandas plot
1个回答
0
投票

默认情况下,索引用作标签。

您可以在绘图之前将列

State
设置为数据框的索引:

df = df.set_index("State")

然后绘图将使用列

State
作为 x 轴的标签:

© www.soinside.com 2019 - 2024. All rights reserved.