0

I am trying to plot a stacked bar plot using matplotlib and pandas and I want to fix the messing it causes when the x-axis are datetype:

df_stack= df_filt.groupby(['MES'])\
             .agg({'SEM_ATESTADOS': 'sum', 'ATESTADOS': 'sum'})\
             .reset_index()

fig, ax = plt.subplots(figsize = (12,6))

fig= df_stack.set_index('MES').plot(kind= 'bar',
                           stacked= True,
                           title= 'Variação de Faltas por mês',
                           figsize= (12,6))

x_dates = df_stack['MES'].dt.strftime('%Y-%m-%d').sort_values().unique()
ax.set_xticklabels(labels=x_dates, rotation=45, ha='right')

plt.xticks(rotation=45, ha= 'right')

plt.show()

The result are two distinct graphs, one of them completely wrong:

enter image description here

The upper plot shows nothing and the x-axis is wrong. The lower graph is correct but the x-axis legends' are messed. I just want it to be in the format %Y-%m-%d. What am i missing here?

BigBen
  • 38,994
  • 6
  • 24
  • 37
Dimitri
  • 97
  • 1
  • 10
  • You're creating two figures, one directly with matplotlib (`fig, ax = plt.subplots(figsize = (12,6))`) and then another when plotting from pandas (`df_stack.set_index('MES').plot(kind= 'bar'...`) – BigBen Apr 28 '22 at 16:17
  • hmm, I see. But how do I tell python to plot the stacked bar plot without calling it from pandas? I thought that `fig= df_stack.plot....` would serve for this – Dimitri Apr 28 '22 at 16:23
  • 2
    `df.stack.plot(....., ax=ax)`. Pass the existing axes as a parameter. – BigBen Apr 28 '22 at 16:27
  • simples as that. thank you very much :)) – Dimitri Apr 28 '22 at 16:30

0 Answers0