python - 如何在 matplotlib 的每个条形顶部显示条形值?
问题描述
我读了几个类似我的问题,但似乎没有人遇到与我相同的问题。
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()
我只在每个组的最后一个栏的顶部获得条形标签,但我需要在每个组的每个条形的顶部显示值,我该怎么做?
解决方案
只需移动循环以在前一个循环for
中写入条形值 ( ) 。问题是您在绘制所有三个条之后编写条值,因此,一旦您退出绘图循环,变量仅包含灰色条的值(数据),因此您只能在顶部看到值的灰色条。我只是在下面写必要的部分。其余代码保持不变。 plt.text
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')
输出
推荐阅读
- sql-server - 如何从数据库生成创建脚本特定的表
- python - 如何在 Django 中显示由外键连接的模型的字段文本而不是 ID?
- python - MQL5 读取文件同时被另一个程序写入
- reactjs - 如何根据给定的示例将列数组值添加为行数组中的新数组?
- javascript - 如何在最新的 Chrome/Firefox 中使用 javascript 在按钮单击时从 HTML 页面运行 bat 文件?
- excel - Microsoft Excel 数据透视表,每行包含多个可筛选项/值
- node.js - 如何在mongoDB中计算总数?
- azure - 数据集类型 json 时 Set-AzureRmDataFactoryV2Dataset 中的 Azure 数据工厂 V2 错误
- docker - OpenGrok docker 镜像中的索引配置在哪里?
- java - 无法映射列表