首页 > 解决方案 > 在不涉及数据帧的情况下按升序对条形图进行排序

问题描述

我有两个列表,我正在使用 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()

编辑:

我意识到这些条是按字母顺序构建的。即使数据是排序的。如何解决这个问题?

标签: pythonmatplotlibbar-chartdata-sciencedata-analysis

解决方案


  • 这两个列表需要结合起来zip,然后按计数排序。
  • 遍历listof以使用注释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()

在此处输入图像描述


推荐阅读