使用 DataFrame绘制男女在不同职业类别下的平均薪资柱状图
时间: 2024-05-14 10:19:58 浏览: 6
首先,我们需要准备好包含男女职业信息和薪资信息的DataFrame。假设我们的DataFrame长这样:
```python
import pandas as pd
data = {
'gender': ['male', 'male', 'female', 'female', 'male', 'female', 'male', 'female'],
'occupation': ['engineer', 'manager', 'doctor', 'lawyer', 'teacher', 'nurse', 'programmer', 'designer'],
'salary': [80000, 100000, 120000, 90000, 60000, 50000, 85000, 70000]
}
df = pd.DataFrame(data)
```
接下来,我们可以使用`groupby`方法对职业类别和性别进行分组,并计算每个组的平均薪资:
```python
grouped = df.groupby(['occupation', 'gender'])['salary'].mean().reset_index()
```
最后,我们可以使用`matplotlib`绘制柱状图:
```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(10, 6))
# 绘制男性平均薪资柱状图
male_data = grouped[grouped['gender'] == 'male']
ax.bar(male_data['occupation'], male_data['salary'], color='blue', label='Male')
# 绘制女性平均薪资柱状图
female_data = grouped[grouped['gender'] == 'female']
ax.bar(female_data['occupation'], female_data['salary'], color='pink', label='Female')
# 设置图表标题和坐标轴标签
ax.set_title('Average salary by occupation and gender')
ax.set_xlabel('Occupation')
ax.set_ylabel('Salary')
# 添加图例
ax.legend()
plt.show()
```
这样就可以得到男女在不同职业类别下的平均薪资柱状图了。