Skip to main content
 首页 » 编程设计

python之如何根据 y 值按降序绘制两个列表

2025年01月19日10shangdawei

我有两个列表。第一个是字符串列表 a

['Agriculture/Forestry/Fisheries/Veterinary Medicine', 
 'Architectural and Town Planning', 
 'Business Administration and Related', ...] 

第二个是 float 列表 b

[66667.0, 
22283.0, 
670091.5, ...] 

当我使用下面的代码绘制它时

import matplotlib.pyplot as plt 
%matplotlib inline 
 
a = ['Agriculture/Forestry/Fisheries/Veterinary Medicine', 
'Architectural and Town Planning', 
'Business Administration and Related', ...] 
b = [66667.0, 
22283.0, 
670091.5, ...] 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(a,b) 
plt.xticks(rotation=90) 

条形图根据列表a 中的字符串按字母顺序排列。 我将如何绘制它以便条形图相对于列表 b 按降序排列?

请您参考如下方法:

一种简单的数据重排方法:

import matplotlib.pyplot as plt 
 
a = [ 
    'Agriculture/Forestry/Fisheries/Veterinary Medicine', 
    'Architectural and Town Planning', 
    'Business Administration and Related' 
] 
 
b = [66667.0, 22283.0, 670091.5] 
 
b, a = zip(*sorted(zip(b, a), reverse=True))  # reverse sort data on 'b' 
 
c = range(len(b)) 
 
fig = plt.figure() 
ax = fig.add_subplot(111) 
ax.bar(c, b) 
plt.xticks(c, a, rotation=90) 
plt.show()