Issue
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.
Solution
No need for the inner loop, just calculate the cummulated bar height and add text there:
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()
Answered By - Psidom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.