简体   繁体   English

更改堆积条形图熊猫中的绘图顺序

[英]Change order of plot in stacked bar plot pandas

I have a dataframe that looks like this:我有一个看起来像这样的数据框:

Category    counts  Decade
0   1.0 55  80s
1   2.0 27  80s
2   3.0 13  80s
3   4.0 7   80s
4   5.0 4   80s
0   1.0 55  90s
1   2.0 31  90s
2   3.0 8   90s
3   5.0 7   90s
4   4.0 3   90s
0   1.0 84  00s
1   2.0 35  00s
2   3.0 10  00s
3   4.0 6   00s
4   5.0 1   00s
0   1.0 137 10s
1   2.0 32  10s
2   3.0 13  10s
3   4.0 12  10s
4   5.0 1   10s

I then plot it as a stacked bar chart:然后我将其绘制为堆积条形图:

df.pivot_table('counts', 'Decade', 'Category', 'first').plot.bar(stacked=True)

However, this organizes my bars not in chronological order.但是,这不是按时间顺序组织我的酒吧。 I realize they are strings, but I figured it would plot the bars from top to bottom in the order of the dataframe.我意识到它们是字符串,但我认为它会按照数据框的顺序从上到下绘制条形图。 How can I force the plot to start at 80s and increase by decade to the right?如何强制情节从 80 年代开始并向右增加十年?

在此处输入图片说明

The pivot_table results in a sorted Index, so you can reindex after the pivot to ensure the correct plotting order. pivot_table产生一个排序的索引,因此您可以在枢轴之后reindex以确保正确的绘图顺序。

(df.pivot_table('counts', 'Decade', 'Category', 'first')
   .reindex(['80s', '90s', '00s', '10s'])
   .plot.bar(stacked=True, figsize=(4,3))

在此处输入图片说明


Another option, you could enforce a custom ordering using a CategoricalDtype :另一种选择,您可以使用CategoricalDtype强制执行自定义排序:

import pandas as pd

my_cat = pd.CategoricalDtype(categories=['80s', '90s', '00s', '10s'], ordered=True)
df['Decade'] = df['Decade'].astype(my_cat)

So now when you pivot it will be ordered properly for plotting without the reindex所以现在当你旋转时,它将被正确排序以进行绘图而无需reindex

df.pivot_table('counts', 'Decade', 'Category', 'first')

#Category  1.0  2.0  3.0  4.0  5.0
#Decade                           
#80s        55   27   13    7    4
#90s        55   31    8    3    7
#00s        84   35   10    6    1
#10s       137   32   13   12    1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM