【问题标题】:Show values in stacked bar chart pandas在堆积条形图 pandas 中显示值
【发布时间】:2021-09-07 10:22:39
【问题描述】:

我有这个熊猫数据框:

   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) 函数绘制了一个堆积条形图

生产和消费以%为单位

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

【问题讨论】:

标签: python pandas dataframe graph


【解决方案1】:

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

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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多