如何在条形图中获得前 5 个值

问题描述 投票:0回答:2

我有一个名为

recent_grads
的数据框,其中包含
Major
Unemloyment_rate
列。如何使用 matplotlib 在条形图中显示失业率最高的前 5 个专业?

fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(1,1,1)
ax.bar(recent_grads["Major"][:5],recent_grads["Unemployment_rate"][:5])
plt.show()
python pandas matplotlib
2个回答
0
投票

如果数据没有聚合,用

groupby.max
,然后
nlargest

(recent_grads.groupby('Major')['Unemployment_rate'].max()
 .nlargest(5).plot.bar()
)

如果数据已经聚合,只需要

nlargest

recent_grads.set_index('Major')['Unemployment_rate'].nlargest(5).plot.bar()

0
投票

您可以使用 pandas 的

.sort_values()
方法以递减的方式按
Unemployment rate
值排序。然后使用
.head()
仅打印前 5 行:

recent_grads.sort_values(by=['Unemployment rate'], ascending=True).head(5)

顺便说一句,5是使用

.head()
的默认显示行数,所以你甚至不需要指定它。
希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.