Horizontal stacked bar chart with annotations

33

# transpose df from the OP so Party is the in the columns and Ward is the index
dft = df.T

# display(dft)
                               Labour  LD  Indep  Green  Tory
Abbey                              16  56      4      0    24
Albrighton                          0   0     32      0    68
Alveley & Claverley                 0  25      0      0    75
Bagley                             30  30      0      0    40
Battlefield                        34   0      0      9    57
Bayston Hill, Column & Sutton      53   4      3      7    33
Belle Vue                          43  28      0      5    24

# plot
ax = dft.plot.barh(stacked=True, figsize=(16, 10))

plt.legend(loc='center left', bbox_to_anchor=(1.0, 0.5))

# annotations:
for p in ax.patches:
    left, bottom, width, height = p.get_bbox().bounds
    if width > 0:
         ax.annotate(f'{width:0.0f}', xy=(left+width/2, bottom+height/2), ha='center', va='center')

Comments

Submit
0 Comments