首页 > 解决方案 > 在堆积条形图 pandas 中显示值

问题描述

我有这个熊猫数据框:

   production  consumption
year        
2013    0.426669    0.573331
2014    0.436364    0.563636
2015    0.419941    0.580059
2016    0.448378    0.551622
2017    0.442212    0.557788
2018    0.422724    0.577276
2019    0.445296    0.554704

我使用df.plot.bar(stacked=True)函数绘制堆积条形图

图形

生产和消费的百分比

是否可以将百分比添加到条形图中?

标签: pythonpandasdataframegraph

解决方案


这比它应该的要难,但它是可行的:

ax = df.plot.bar(stacked=True)
labels = [f'{i:.0%}' for i in df.to_numpy().flatten(order='F')]

for i, patch in enumerate(ax.patches):
    x, y = patch.get_xy()
    x += patch.get_width() / 2
    y += patch.get_height() / 2
    ax.annotate(labels[i], (x, y), ha='center', va='center', c='white')

结果:

在此处输入图像描述


推荐阅读