我正在尝试对pandas plot x轴中的分类变量进行排序。我试着从pandas数据帧本身进行排序,但我只能按字母顺序排序。我在plot中看不到以这种方式排序的选项。我尝试按以下顺序获得x轴: Mon,Tue,Wed,Thru,Fri,Sat,Sun。我该怎么做?
df = data_df.groupby(['name1','weekday']).sum().reset_index()
s = (df.pivot_table(
index='weekday', columns='name1', values='count', aggfunc='sum'))
s.plot(kind='bar', stacked=True,figsize=(20,10),rot=0)
plt.show()

查找此输出
发布于 2020-03-26 08:53:45
据我所知,您的df和s本质上是相同的。此外,您还可以使用reindex命令,然后绘制:
weekdays = ['Monday','Tuesday','Wednesday','Thursday',
'Friday','Saturday','Sunday']
# sample data
np.random.seed(1)
data_df = pd.DataFrame({
'name1':np.random.randint(0,3, 100),
'weekday':np.random.choice(weekdays, 100),
'count':np.random.randint(3,100)
})
# groupby and take sum
s = (data_df.groupby(['name1','weekday'])
.sum().unstack('name1')
.reindex(weekdays) # here is the key to get the correct order
)
# plot
s.plot.bar(stacked=True)输出:

https://stackoverflow.com/questions/60858366
复制相似问题