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

2024-09-23 00:18:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

第二个是浮动列表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的降序排列


Tags: and字符串列表pltbusinessplanningrelatedadministration
3条回答

这就是你想要做的:

import matplotlib.pyplot as plt
import pandas as pd
%matplotlib inline

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

values = [66667.0,22283.0,670091.5]

df = pd.DataFrame(columns=['category', 'value'])
df = df.append([{"category":a, "value":b} for a, b in zip(categories, values)])

df.sort_values('value', ascending=False)[['category','value']].plot.bar()

enter image description here

使用numpy

  • list(zip(list_name, list_count))将两个列表压缩为元组列表
    • 将元组列表转换为带有dtypes^{}
  • ^{}按升序排序(从最小到最大)
  • [::-1]反转数组
  • 好处是,matplotlib很容易接受数组,并且numpy列可以与其名称一起传递
import numpy as np
import matplotlib.pyplot as plt

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

values = [66667.0, 22283.0, 670091.5]

# get the length of the longest string in text, for the numpy str dtype
# this is only necessary if make sure the entire string is included in the array
str_len = max([len(t) for t in text])

# create numpy array with dtypes
t = np.array(list(zip(text, values)), dtype = [('text', f'S{str_len}'), ('values', int)])

# sort array
t = np.sort(t, order=['values'])[::-1]

# plot
plt.bar(x=t['text'], height=t['values'])
plt.xticks(rotation=90)

enter image description here

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

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()

enter image description here

相关问题 更多 >