python - 在不涉及数据帧的情况下按升序对条形图进行排序
问题描述
我有两个列表,我正在使用 matplotlib 绘制图表。目前,条形图以列表的编写方式进行组织。我想自动将它们设置为升序/降序。我该怎么做?
industries = ['Manufacturing', 'Food', 'Eco']
counts = [12,78,1]
plt.figure(figsize=(16,6))
bars = plt.bar(industries, counts, width=0.2, bottom=None, align='center', data=None)
plt.xlim(-0.9, len(industries) - 1 + 0.9)
for i in range(len(counts)):
percentage = ((counts[i]/(total))*100)
plt.annotate(percentage, xy=(industries[i], counts[i] + 10), ha='center')
plt.show()
编辑:
我意识到这些条是按字母顺序构建的。即使数据是排序的。如何解决这个问题?
解决方案
- 这两个列表需要结合起来
zip
,然后按计数排序。 - 遍历
list
of以使用注释tuples
按顺序添加条形图。reverse
industries = ['Manufacturing', 'Food', 'Eco']
counts = [12, 78, 1]
tot = sum(counts)
# combine the two lists with zip and then reverse sort them
data = sorted(zip(industries, counts), key=lambda v: v[1], reverse=True)
plt.figure(figsize=(16, 6))
for (i, c) in data: # unpack and plot each tuple in sorted order
bars = plt.bar(i, c, width=0.2, bottom=None, align='center', data=None, color='g')
plt.annotate(f'{(c/tot)*100:0.02f}%\n', xy=(i, c), va='center', ha='center')
plt.xlim(-0.9, len(industries) - 1 + 0.9)
plt.show()
推荐阅读
- javascript - 如何使用 JavaScript 为 discord bot 从这个数组中选择一个随机值?
- html - 如何在输入类型=“文本”的移动设备上强制使用数字键盘
- java - 如何在约束布局中以编程方式移动视图(按钮)?
- ios - 自定义保护语句中的 UITableViewCell 文本
- mips - .data 部分 MIPS 中缺少数组
- python - 如何从字典中创建每个键的排列?
- r - R dcast 和日期
- rx-java - 将Flowable分成2个,处理2个流,但一个依赖于另一个?
- python - 在 html 文件中,如何将 DateTime 格式转换为 Hrs:Min?
- bash - 用于清除历史记录的 Bash 脚本,关于更好解决方案的问题