You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Matplotlib绘制DataFrame中失业率Top5专业的柱状图

如何用Matplotlib绘制失业率最高的前5个专业柱状图?

你提供的代码直接取了DataFrame的前5行,但这未必是失业率最高的5个专业——得先按失业率从高到低排序,再取前5条数据才行。

以下是修正后的完整实现:

import matplotlib.pyplot as plt
import pandas as pd

# 按失业率降序排序,提取前5个专业
top5_unemployed = recent_grads.sort_values(by="Unemployment_rate", ascending=False).head(5)

# 创建画布与子图
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 1, 1)

# 绘制柱状图
ax.bar(top5_unemployed["Major"], top5_unemployed["Unemployment_rate"])

# 优化图表可读性
ax.set_title("失业率最高的前5个专业")
ax.set_xlabel("专业名称")
ax.set_ylabel("失业率")
plt.xticks(rotation=45, ha="right")  # 旋转x轴标签,避免文字重叠
plt.tight_layout()  # 自动调整布局,防止标签被截断

plt.show()

关键细节说明:

  • sort_values(by="Unemployment_rate", ascending=False):通过降序排序,确保筛选出的是失业率最高的专业
  • head(5):提取排序后的前5条目标数据
  • plt.xticks(rotation=45, ha="right"):解决专业名称过长导致的标签重叠问题
  • plt.tight_layout():自动调整图表元素位置,避免边缘内容被截断

内容的提问来源于stack exchange,提问作者maja kralj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:43:20