如何在matplotlib的每个柱形上方显示柱形值? [英] How can I display the bar value on top of each bar on matplotlib?

查看:122
本文介绍了如何在matplotlib的每个柱形上方显示柱形值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I read a couple of questions like mine, but no one seems to have the same problem that I'm experiencing.

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

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

I'm getting the bar label only on top of the last bar of each group, but i need to display the value on top of each bar of each group, how can I do this?

当前情节:

推荐答案

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

Just move your for loop for writing the bar values (plt.text) inside the previous for loop. The problem is that you write the bar values after plotting all the three bars and so, once you come out of the plotting for loop, the variable bars contains only the values of the gray bars (the LinkedIn data) and hence you see the values only on top of gray bars. I am just writing the necessary part below. rest code remains the same.

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

输出

这篇关于如何在matplotlib的每个柱形上方显示柱形值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆