1

It sounds simple but I cant get a stacked bar chart. I got a series after grouping by a column in a dataframe.

s1 = df_sort.groupby('loan_status')['count_loans'].sum()
s1

loan_status
Fully paid        8045
Not fully paid    1533
Name: count_loans, dtype: int64

I have tried

s1.T.plot.bar(stacked=True)

s1.plot(kind="bar", stacked=True)

which produces two individual bars?

thanks.

Zephyr
  • 11,891
  • 53
  • 45
  • 80
Bluetail
  • 1,093
  • 2
  • 13
  • 27

2 Answers2

1

You should change the groupby line to:

df = df.groupby(by = 'loan_status').sum().T

Then you can plot with:

df.plot(kind = 'bar', stacked = True)

plt.show()

enter image description here

Zephyr
  • 11,891
  • 53
  • 45
  • 80
  • I think you change the final values of the OP? – Corralien Sep 22 '21 at 21:04
  • Yes because I randomly generated an other dataframe from which group-by, so values are different from the ones reported in the question – Zephyr Sep 22 '21 at 21:18
  • thanks! do you know how to remove 'count_loans'? – Bluetail Sep 23 '21 at 18:33
  • You should assign `df.plot` as `ax = df.plot(kind = 'bar', stacked = True)` and then you can remove the tick label with `ax.set_xticklabels('')` – Zephyr Sep 23 '21 at 18:52
  • ok :) thank you. I am now trying to put the percentage values on it - maybe you know how to do it as well? https://stackoverflow.com/questions/69306442/stacked-bar-showing-percentage-values-for-2-variables-in-matplotlib/69306610#69306610 – Bluetail Sep 24 '21 at 20:18
1

You have to convert your Series to a DataFrame else you can't transpose:

s1.to_frame().T.plot(kind='bar', stacked=True, rot=0)
plt.show()

stackbar

Corralien
  • 109,409
  • 8
  • 28
  • 52