Home > Software design >  Python: Stack bar chart, how can I stack by year from column?
Python: Stack bar chart, how can I stack by year from column?

Time:11-07

Hi all am trying to create a stacked bar chart that shows every day of the Year (1 through to 365), with the stacks representing the Year.

My data looks like this:

enter image description here

I have put together the following which works for all Days/Years:

daychart = data.groupby(['Day'], as_index=False, sort=False).agg(Count=('Day','size'))
plt.figure(figsize=(20,4))
matplotlib.pyplot.bar(x="Day", height="Count", data=daychart)
plt.show()

... and looks like this:

enter image description here

What I would like to do now is show 2019 in Red, stacked on top of Blue (2020).

I have tried the following but it is falling in a heap:

b2019 = data.groupby([data['Year']=='2019']['Day'], as_index=False, sort=False).agg(Count=('Day','size'))
b2020 = data.groupby([data['Year']=='2020']['Day'], as_index=False, sort=False).agg(Count=('Day','size'))

plt.figure(figsize=(20,4))
matplotlib.pyplot.bar(x="Day", height="Count", data=b2019, color='r')
matplotlib.pyplot.bar(x="Day", height="Count", data=b2020, color='b')
plt.show()

Error:

enter image description here

Can anybody explain where I am going wrong on this?

Thank you :)

CodePudding user response:

Try query

b2019 = data.query('Year == 2019').groupby('Day', as_index=False, sort=False).agg(Count=('Day','size'))
b2020 = data.query('Year == 2020').groupby('Day', as_index=False, sort=False).agg(Count=('Day','size'))
  • Related