Skip to main content
 首页 » 编程设计

python之使用 matplotlib 在每个堆叠条上的 Y 值

2025年05月04日26qlqwjy

对在图表上显示实际值有疑问。我确实有一张打印图表,需要显示每个堆叠条形图的值。如何显示这些值?

我尝试了 ax.text 函数,但它没有给出预期的结果(见图)。由于图表标准化为 1,我需要显示每个堆叠条形图的实际值(顶部是总数,它应该拆分为每个条形图 - 第一个条形图应该有 1 个数字 7,第二个条形图应该有 3 个数字,其中数字41 被每个颜色条的大小分开)。可以这样做吗?

我的代码是如何得出多个堆叠条的:

def autolabel(rects): 
    # attach some text labels 
    for rect in rects: 
        height = rect.get_height() 
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height), 
                ha='center', va='bottom') 
 
p = [] # list of bar properties 
def create_subplot(matrix, colors, axis): 
    bar_renderers = [] 
    ind = np.arange(matrix.shape[1]) 
    bottoms = np.cumsum(np.vstack((np.zeros(matrix.shape[1]), matrix)), axis=0)[:-1] 
    for i, row in enumerate(matrix): 
        print bottoms[i] 
        r = axis.bar(ind, row, width=0.5, color=colors[i], bottom=bottoms[i]) 
        bar_renderers.append(r) 
        autolabel(r) 
    #axis.set_title(title,fontsize=28) 
    return bar_renderers 
 
p.extend(create_subplot(nauja_matrica,spalvos, ax)) 

请您参考如下方法:

您可以使用 ax.text 函数显示每个堆叠条的值。只需对您的代码进行少量更正即可获得所需的结果。其实只要把autolabel函数替换成下面的代码即可:

def autolabel(rects): 
    # Attach some text labels. 
    for rect in rects: 
        ax.text(rect.get_x() + rect.get_width() / 2., 
                rect.get_y() + rect.get_height() / 2., 
                '%f'%rect.get_height(), 
                ha = 'center', 
                va = 'center') 

它将纠正标签的垂直定位并给出:

如果您想更改标签以获得非标准化值,则需要做更多的工作。最简单的解决方案是将附加参数 values(包含未规范化的值)传递给 autolabel 函数。代码将是:

def autolabel(rects, values): 
    # Attach some text labels. 
    for (rect, value) in zip(rects, values): 
        ax.text(rect.get_x() + rect.get_width() / 2., 
                rect.get_y() + rect.get_height() / 2., 
                '%d'%value, 
                ha = 'center', 
                va = 'center') 

希望对您有所帮助。