如何在 Pandas 数据框中没有 header 的情况下绘制带有总计的条形图?

How can I plot a bar with totals without the header in Pandas dataframe?

我想根据我的 df 绘制一个带有总标签的条形图。但是,总数出现了一行。该图包括 header 行,因此总数放错了地方。这是我的 df 和代码的 header 和前 3 行:

    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")

因为你的dataframe的索引是从1开始的。所以,你需要将文本的x-coordinate偏移1:

ax.text(totals.index[i]-1, total + y_offset, round(total), ha="center")