1

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?

Ando Jurai
  • 1,003
  • 2
  • 14
  • 29

1 Answers1

1

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
Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Thanks, I don't understand why is this that you can't do it from the start (it seems pretty basic, I actually tried to set origin as index instead of date, or to pass by a pivot table -getting somewhat the kind of result like the output of reshape, but not the right one) nor how it works (because I set index with date precisely to get it as x, so why doesn't it display the origin there is a great mystery for me). But I guess it should work, so I'm really glad. – Ando Jurai Feb 15 '23 at 23:49