[英]Label stacked bar with autolabel function
由于某种原因,我想生成一个堆叠的条形图,该条形图需要在每个部分的右侧设置。 此处显示一个示意图:
每个部分均以其值和百分比作为标签。
这是我用自动标签功能绘制堆积条形图的解决方案。
AMOUNT_LOOP = np.array([GM[0]+OM[0]+TEO[0],GM[1]+OM[1]+TEO[1],GM[2]+OM[2]+TEO[2]])
## data
GM = np.array([ 26.24592078, 51.76195669, 38.8572158 ])
OM = np.array([ 21.13405649, 12.71185216, 14.84377391])
TEO = np.array([ 0.52274901, 0.57721648, 0.52718344])
def autolabel(rects, ax):
(y_bottom, y_top) = ax.get_ylim()
y_height = y_top - y_bottom
for i,rect in enumerate(rects) :
height = rect.get_height()
label_position = height*0.5 + (y_height * 0.01)
label_ = "%2.1f" % (height/AMOUNT_LOOP[i]*100)
label =label_+'%'
ax.text(rect.get_x()+1.05 + rect.get_width()/2., label_position-0.5,
'%s' % str(label),
ha='center', va='bottom')
l=plt.Line2D((rect.get_x()+1.15, rect.get_x()+1.3), (label_position-2.5, label_position), lw=0.75,color ='k')
plt.gca().add_line(l)
cs = ['#a6cee3','#C2C4C6','#F9F2AA',]
fig, ax = plt.subplots()
y_pos = np.array([1,3.75,6.45])
rect1 = ax.bar(y_pos, GM, width = 1.2, color = cs[0], label = 'GM')
autolabel(rect1,ax)
rect2 = ax.bar(y_pos, OM, width = 1.2, bottom=GM, color = cs[1], label = 'OM')
autolabel(rect2,ax)
rect3 = ax.bar(y_pos, TEO, width = 1.2, bottom=GM+OM, color = cs[2], label = 'TEO')
autolabel(rect3,ax)
ax.set_xlim(0,8.5)
plt.show()
结果显示如下:
因此,问题是我的标签高度不是从其相应部分的底线开始。 我想生成一个函数,该函数可以检测堆叠位置并将基础条形的高度添加为新的Y位置。
我还没有考虑过任何解决方案。
任何建议或指南将不胜感激!
以下应该可以解决问题:
import numpy as np
from matplotlib import pyplot as plt
## data
GM = np.array([ 26.24592078, 51.76195669, 38.8572158 ])
OM = np.array([ 21.13405649, 12.71185216, 14.84377391])
TEO = np.array([ 0.52274901, 0.57721648, 0.52718344])
def autolabel(rects, ax):
for rect in rects:
y_val = rect.get_y() + rect.get_height() - rect.get_height()/2
ax.text(rect.get_x()+1.05 + rect.get_width()/2., y_val,
str(rect.get_height()),
ha='center', va='bottom')
cs = ['#a6cee3','#C2C4C6','#F9F2AA',]
fig, ax = plt.subplots()
y_pos = np.array([1,3.75,6.45])
rect1 = ax.bar(y_pos, GM, width = 1.2, color = cs[0], label = 'GM')
autolabel(rect1, ax)
rect2 = ax.bar(y_pos, OM, width = 1.2, bottom=GM, color = cs[1], label = 'OM')
autolabel(rect2, ax)
rect3 = ax.bar(y_pos, TEO, width = 1.2, bottom=GM+OM, color = cs[2], label = 'TEO')
autolabel(rect3, ax)
ax.set_xlim(0,8.5)
plt.show()
调用rect.get_y() + rect.get_height()
获得每个条的y值。 get_y
是基数, get_height
是高度。 - rect.get_height()/2
获得每个条的中心。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.