如何在分组柱状图的每个柱子顶部显示条形值

4

我看到了一些和我的问题类似的提问,但是似乎没有人遇到我正在经历的问题。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

facebook_users = [10, 14, 19, 17, 17, 13, 10]
twitter_users = [10, 18, 22, 17, 15, 11, 7]
linkedin_users = [4, 10, 20, 18, 20, 17, 11]

group = ['13 - 17', '18 - 24', '25 - 34', '35 - 44', '45 - 54', '55 - 65', '65+']

mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=["#3B5998", "c", "grey"])

def bar_group(classes, values, width=0.8):
    plt.xlabel('Age groups (in years)', weight='semibold')
    plt.ylabel('Percentage of users (%)', weight='semibold')
    total_data = len(values)
    classes_num = np.arange(len(classes))
    for i in range(total_data):
        bars = plt.bar(classes_num - width / 2. + i / total_data * width, values[i], 
                width=width / total_data, align="edge", animated=0.4)
    plt.xticks(classes_num, classes, rotation=-45, size=11)
    plt.legend(['Facebook', 'Twitter', 'LinkedIn'])

    for rect in bars:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width()/2.0, height, '%d' % int(height), ha='center', va='bottom')


bar_group(group, [facebook_users, twitter_users, linkedin_users])

plt.show()

我只在每组中的最后一根柱子上得到了标签,但我需要在每组的每个柱子上显示值,我该怎么做?

当前的绘图: 这是我得到的内容:


如何绘制和注释分组条形图展示了一种更简单的方法来注释分组条形图,使用 plt.bar_label - Trenton McKinney
移除for rect in bars循环。然后添加ax = plt.gca(),接着是for p in ax.containers: ax.bar_label(p, label_type='edge')。此方法适用于matplotlib v3.4.0及以上版本。请参见代码和图形 - Trenton McKinney
1个回答

5
只需将写入柱形值(plt.text)的for循环移至先前的for循环中。问题在于,您在绘制所有三个条形图后编写条形值,因此,一旦退出绘图for循环,变量bars仅包含灰色条形(LinkedIn数据)的值,因此您只能在灰色条形顶部看到这些值。下面仅编写必要部分,其余代码保持不变。
for i in range(total_data):
    bars = plt.bar(classes_num - width / 2. + i / total_data * width, values[i], 
            width=width / total_data, align="edge", animated=0.4)
    for rect in bars:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width()/2.0, height, '%d' % int(height), ha='center', va='bottom')

输出

在此处输入图片描述


这段内容是关于“输出”的。其中包含一张图片,如上所示。

1
非常感谢您! - Lucas Figueiredo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接