分组 pandas 系列的堆积条形图 [英] stacked bar chart for grouped pandas series
问题描述
有一个如下所示的数据框:
Hi have a dataframe that looks like this:
ID Date Total_Amount priority
1 2007 4488 High
2 2007 40981 Low
3 2017 450 Medium
4 2008 1000 Low
每行是一个新人(ID),并且各行显示他们每年花费多少(总计).
each row is a new person (ID) and the rows show how much they spent per year (total amount).
我想创建一个条形图,在x轴上使用年,将Total_Amount作为y轴高度,但是需要按优先级对其进行堆叠.例如如果2007年有10笔支出的钱,其Total_Amount金额为100,000英镑,则根据优先级,栏的高度必须为100,000堆叠(例如5笔高,4笔低和1笔中等).
I want to create a bar chart with the years on the x-axis and the Total_Amount as the y-axis height but it needs to be stacked by priority. e.g. if 10 spent money in 2007 and their Total_Amount sum is £100,000, the height of the bar needs to be 100,000 stacked by priority( e.g. 5 may have been high, 4 low and 1 medium).
我尝试使用交叉表,其中日期作为行,优先级作为列,但是我没有获得Total_Amount花费的数据框,而每个优先级的人数却得到一个数据框.
I tried using crosstab with date as row and priority as columns but I don't get a dataframe for Total_Amount spent, I get one for the number of people in each priority.
推荐答案
您可以使用 groupby()
,然后使用 unstack()
:
You can use groupby()
and then unstack()
:
df2 = df.groupby(['Date','priority'])['Total_Amount'].sum().unstack('priority').fillna(0)
df2.plot(kind='bar', stacked=True)
产生:
这篇关于分组 pandas 系列的堆积条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!