1

I saw a code for a stacked percentage bar plot in another post, however, am having trouble adopting it for my plot. Display totals and percentage in stacked bar chart using DataFrame.plot


data = {'Paid':[8045],'Not Paid':[1533]}
df = pd.DataFrame(data, index = [''])
df['Total'] = df['Paid']+df['Not Paid']

df_rel = (df[df.columns[0:2]].div(df.iloc[0, 2])*100).round(2)
df_rel

So I want to build a stacked bar showing the percentage values for each of my two variables on it:

df_rel.plot( kind='bar',stacked = True,mark_right = True) # this is ok

for n in df_rel:
    for i, (a,b,c) in enumerate(zip(df_rel.iloc[:,:][n], df[n], df_rel[n])):
         plt.text(a -b / 2, i, str(c) + '%', va = 'center', ha = 'center')  # this gives an error.

Can somebody help me figure out whats wrong? I'm getting 'ValueError: Image size of 1318810x237 pixels is too large.'

Also this approach seems complicated maybe someone knows a better way.

Bluetail
  • 1,093
  • 2
  • 13
  • 27

1 Answers1

2

No need for the inner loop, just calculate the cummulated bar height and add text there:

Full example

df_rel.plot( kind='bar',stacked = True,mark_right = True) # this is ok
h = 0
for col in df_rel:
    h += (p := df_rel[col].iat[0])      # calculate current bar height
    plt.text(0, h - p / 2, f'{p}%', va='center', ha='center')
plt.show()

enter image description here

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • It says invalid syntax? I have python 3.6.13 thats why its not recognising the ' :=' operator. do you know another way to do it? – Bluetail Sep 24 '21 at 20:11
  • `:=` does nothing but assign values in line. If you are using older versions of python, you can separate it into two lines: `p = df_rel[col].iat[0]; h += p` – Psidom Sep 24 '21 at 20:30