You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为分组柱状图的每个类别标注占比百分比

分组柱状图添加占比百分比标注需求

我用以下代码生成了一幅分组柱状图,希望为每个user的Negative、Neutral、Positive三类数据标注占比百分比,使每个user的三类占比总和约为100%,效果如下方示例中user1和user2所示:

目标效果

原始代码:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

users = ['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7',\
         'user8', 'user9', 'user10', 'user11', 'user12']
NEG = [433, 1469, 1348, 2311, 522, 924, 54, 720, 317, 135, 388, 9]
NEU = [2529, 4599, 4617, 4297, 1782, 2742, 61, 2640, 1031, 404, 1723, 76]
POS = [611, 1149, 1262, 1378, 411, 382, 29, 513, 421, 101, 584, 49]

data = {'Negative': NEG, 'Neutral': NEU, 'Positive': POS}
df = pd.DataFrame(data, index=users)
ax = df.plot(kind='bar', ylabel='Number of Messages\nw/ <= 128 Characters',\
             xlabel='Username', title='Discord Sentiment Analysis',\
             color=['coral', 'khaki', 'skyblue'])

plt.tight_layout()
plt.show()

三次尝试及效果

尝试1

ax = df.plot(kind='bar', ylabel='Number of Messages\nw/ <= 128 Characters',\
             xlabel='Username', title='Discord Sentiment Analysis',\
             color=['coral', 'khaki', 'skyblue'])

for p in ax.containers:
    ax.bar_label(p, fmt='%.1f%%', label_type='edge')

plt.tight_layout()
plt.show()

尝试1效果

尝试2

ax = df.plot(kind='bar', ylabel='Number of Messages\nw/ <= 128 Characters',\
             xlabel='Username', title='Discord Sentiment Analysis',\
             color=['coral', 'khaki', 'skyblue'])

for p in ax.patches:
    width = p.get_width()
    height = p.get_height()
    x, y = p.get_xy() 
    ax.annotate(f'{height:.0%}', (x + width/2, y + height*1.02), ha='center')

plt.tight_layout()
plt.show()

尝试2效果

尝试3

ax = df.plot(kind='bar', ylabel='Number of Messages\nw/ <= 128 Characters',\
             xlabel='Username', title='Discord Sentiment Analysis',\
             color=['coral', 'khaki', 'skyblue'])

for p in ax.containers:
    ax.bar_label(p, fmt='%.1f%%', label_type='edge')
    
plt.tight_layout()
plt.show()

尝试3效果

请帮忙实现正确的百分比标注。


内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:02:47