0

I am plotting a percentage stacked bar chart using the following code:

df_q1 = df.groupby(['Q01_response', 'Year']).size().reset_index().pivot(columns='Q01_response', index='Year', values=0)
df_q1 = df_q1[['Always', 'Often','Sometimes','Never']]
stacked_data = df_q1.apply(lambda x: x*100/sum(x), axis=1)
stacked_data.plot(kind="bar", stacked=True, color=['#009933', '#99ff99', '#ff99ff','#ff6666'],figsize=(15, 5))
plt.legend(bbox_to_anchor=(1.05, 1.0), loc='upper left')
#plt.title("Mince Pie Consumption Breakdown")
plt.xlabel("Year")
plt.ylabel("Responses (%)")

graph How can I add the bar labels in percentages?

Asra Khalid
  • 177
  • 1
  • 18

1 Answers1

1

I was able to add labels by saving the graph in ax and adding this block of code:

  for p in ax.patches:
        width, height = p.get_width(), p.get_height()
        x, y = p.get_xy() 
        ax.text(x+width/2, 
                y+height/2, 
                '{:.0f} %'.format(height), 
                horizontalalignment='center', 
                verticalalignment='center')

graph

Asra Khalid
  • 177
  • 1
  • 18