我正在尝试在熊猫图x轴上对分类变量进行排序。我尝试从pandas数据框本身进行排序,但只能按字母顺序对其进行排序。我没有看到图中的选项以这种方式对其进行排序。 我试图按以下顺序获取x轴:[周一,周二,周三,周四,周五,周六,周日]。我该怎么办?
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()
寻找此输出
答案 0 :(得分:1)
据我所知,您的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)
输出: