Displaying a shared bar chart from groupby results

Question:

I have this type of Dataframe :

    origin  delta
month                
2021-09  admin  -1000
2021-09    ext     20
2021-10    ext    648
2021-11  admin  -1000
2021-11    ext    590
monthframe (32,3)

(I reprocessed "month" index from dates in a colum, parsed as datetime initially)
I tried to reproduce
Pandas dataframe groupby plot
Pandas groupby results on the same plot

with

monthframe.groupby("origin").plot(kind="bar",stacked=True, legend=True, xlabel="Month", ylabel="Delta", layout=(20,10),subplots=False)

setting month as index before so that it will work as x.

But I can’t get it to display bars in the same graph, with various colors.
I only have one graph when I do

monthframe.plot(kind="bar",stacked=True, legend=True, xlabel="Month", ylabel="Delta", layout=(20,10),subplots=False)

but then all origins are merged into the same months, all is blue and it really isn’t informative.

I tried everything I could find (setting axes before; etc, but the plot doesn’t even take its named arguments into account).

What to do please?

Asked By: Ando Jurai

||

Answers:

With matplotlib, you have to reshape your dataframe:

ax = (monthframe.set_index('origin', append=True)['delta'].unstack()
                .plot(kind='bar', stacked=True, legend=True, rot=45, 
                      xlabel='Mois', ylabel='Consommation'))
plt.tight_layout()
plt.show()

enter image description here

Output of reshape:

>>> monthframe.set_index('origin', append=True)['delta'].unstack()

origin    admin    ext
month                 
2021-09 -1000.0   20.0
2021-10     NaN  648.0
2021-11 -1000.0  590.0
Answered By: Corralien
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.