簡體   English   中英

具有自動標簽功能的標簽堆疊條

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM