如何在matplotlib的每个柱上方显示柱值?

时间:2018-08-19 15:20:46

标签: python numpy matplotlib plot bar-chart

我读了像我这样的几个问题,但是似乎没有人遇到我遇到的相同问题。

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

我只在每个组的最后一个条的顶部显示条标签,但是我需要在每个组的每个条的顶部显示值,我该怎么做?

当前情节: Here's what I'm getting:

1 个答案:

答案 0 :(得分:4)

只需移动您的for循环以在上一个plt.text循环内写入条形值(for)。问题是您在绘制所有三个条形图之后写了条形图值,因此,一旦退出绘制for循环,变量bars仅包含灰色条形图的值({ {1}}数据),因此您只能在灰色条顶部看到这些值。我只是在下面写必要的部分。其余代码保持不变。

LinkedIn

输出

enter image description here