I want to plot a bar with total labels based on my df. But, the totals appear off by one row. The plot includes the header row, so the totals are misplaced. Here is the header and first 3 rows of my df and my code:
Ethnicity Bachelor Master Doctorate
1 Chinese 278270 101555 21015
2 Black 82855 38475 6350
3 Filipino 182845 8845 885
ax = df.plot(kind="bar", stacked=True, figsize=(15,6), width=.5)
totals = df.sum(axis=1)
y_offset = 4
for i, total in enumerate(totals):
ax.text(totals.index[i], total y_offset, round(total), ha="center")
CodePudding user response:
It's because your dataframe's index is starting from 1. So, you need to offset by 1 the x-coordinate of the texts:
ax.text(totals.index[i]-1, total y_offset, round(total), ha="center")