![](/img/trans.png)
[英]Plotting Multiple Histograms in Matplotlib - Colors or side-by-side bars
[英]Percentage Annotation Matplotlib Bars side-by-side
我創建了下圖,但我想作為注釋添加上面每個條的百分比,而不是數字。 在這種並排的三個酒吧的情況下,有人可以幫助如何做到這一點。 注意:我希望每組三個條形的百分比總和為 100%。 我只知道如何為每個類別執行此操作...
fig = plt.figure(figsize=(15, 8));
ax5 = fig.add_subplot(1, 1, 1);
ax5.set_xticklabels(ff.index.tolist(), size=12)
# Custom Y axis-ticks
y_ticks = np.arange(0, 400, 50)
yrange = (y_ticks[0], y_ticks[-1])
ax5.set_ylim(yrange)
ax5.set_yticklabels(y_ticks, size = 12)
ax5.set_yticks(y_ticks)
# set the xlim
ax5.set_xlim(0, len(labels))
# get your locations
dim = np.arange(0.35,len(labels),1);
# set the locations of the xticks to be on the integers
ax5.set_xticks(dim)
# Custom X - label
ax5.set_xlabel('Mode of Information', size=16, fontweight='bold')
# Custom X - label
ax5.set_ylabel('Number of volunteers', size=16, fontweight='bold')
rects1 = ax5.bar(x + width, Rem, width, label='Remained the same', color='coral',
edgecolor='black')
rects2 = ax5.bar(x + (width*2), Inc, width, label='Increased', color='forestgreen',
edgecolor='black')
rects3 = ax5.bar(x + (width*3), Dec, width, label='Decreased', color='royalblue',
edgecolor='black')
for i,rect in enumerate(rects1): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
for i,rect in enumerate(rects2): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
for i,rect in enumerate(rects3): # for each bar
height = rect.get_height()
ax5.text(rect.get_x() + rect.get_width() / 2, rect.get_height() + 3, '%s'% (height),
ha='center', va='bottom', color = 'black', size = 12)
您可以制作一個totals
列表,為您提供每個組內的總計:
totals = [x.get_height() + y.get_height() + z.get_height()
for x, y, z in zip(rects1, rects2, rects3)]
然后在三個注釋循環中,將height
文本除以totals[i]
:
# '%s' % (height) # old
'%.1f%%' % (100 * height / totals[i]) # new
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.