带有自动标记功能的标签堆叠条

时间:2016-12-01 02:09:04

标签: python python-2.7 matplotlib

我的项目

出于某种原因,我想生成一个堆积条形图,其中需要在每个部分的右侧设置数字。此处显示了插图:

enter image description here

每个部分都以其值和百分比作为标签。

我的尝试

这是我用自动标记函数绘制堆积条的解决方案。

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

结果显示如下:

enter image description here

我的问题

所以,问题是我的标签高度不是来自其相应部分的底线。我想生成一个可以检测堆叠位置的函数,并将底层条的数量高度添加为新的Y位置。

我没有想过任何解决方案。

任何建议或指南都会很感激!

1 个答案:

答案 0 :(得分:2)

以下应该可以解决问题:

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获得每个酒吧的中心。

Here is example image