如何在Python中将最小的条形图放在堆叠条形图的顶部

pxy2qtax  于 2023-11-15  发布在  Python
关注(0)|答案(1)|浏览(164)

我有一个堆叠的条形图,但我想把它颠倒过来,把最小的条形放在上面。下面是我的代码:

  1. import pandas as pd
  2. data = {'fields': ['LastName', 'Race', 'Email', 'MidName', 'StreetAddress', 'Phone', 'State', 'FirstName', 'Gender', 'Expiration', 'StreetAddress'],
  3. 'Status': ['complete', 'missing', 'missing', 'complete', 'complete', 'missing', 'missing', 'complete', 'complete', 'complete', 'missing'],
  4. 'count': [27399, 146, 24225, 26078, 27269, 59, 28, 27399, 27403, 14017, 134]}
  5. df = pd.DataFrame(data)
  6. dfp = df.pivot(index='Status', columns='fields', values='count')
  7. tot = dfp.sum(axis=1)
  8. per = dfp.div(tot, axis=0).mul(100).round(2)
  9. ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
  10. ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
  11. ax = per.plot(kind='bar', stacked=True, figsize=(8, 6), rot=0)
  12. for p in ax.patches:
  13. width, height = p.get_width(), p.get_height()
  14. x, y = p.get_xy()
  15. ax.text(x+width/2,
  16. y+height/2,
  17. '{:.0f} %'.format(height),
  18. horizontalalignment='center',
  19. verticalalignment='center')
  20. ax.legend(bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)

字符串

sg3maiej

sg3maiej1#

我所要做的就是用[::-1]颠倒列的顺序,它工作得很好。它从下到上升序排序。我应该在我的原始代码中指定列按百分比.df[df.columns[::-1]]升序排列。
x1c 0d1x的数据

相关问题