我有一个名为
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()
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()
您可以使用 pandas 的
.sort_values()
方法以递减的方式按 Unemployment rate
值排序。然后使用 .head()
仅打印前 5 行:
recent_grads.sort_values(by=['Unemployment rate'], ascending=True).head(5)
顺便说一句,5是使用
.head()
的默认显示行数,所以你甚至不需要指定它。