gpt4 book ai didi

python - 如何在分组条形图中的每个条形图顶部显示条形值

转载 作者:太空狗 更新时间:2023-10-30 02:52:50 25 4
gpt4 key购买 nike

我阅读了几个与我类似的问题,但似乎没有人遇到与我遇到的问题相同的问题。

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:

最佳答案

只需将您的 for 循环移动到之前的 for 循环中写入条值 (plt.text)。问题是您在绘制所有三个柱后写入柱值,因此,一旦您退出绘图 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')

输出

enter image description here

关于python - 如何在分组条形图中的每个条形图顶部显示条形值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51919113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com