import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd def student(): # ********* Begin *********# # ********* End *********#
时间: 2025-06-03 22:19:39 浏览: 28
### 使用 Matplotlib、Seaborn、NumPy 和 Pandas 实现学生数据可视化的代码示例
以下是一个完整的代码示例,展示如何使用 Matplotlib、Seaborn、NumPy 和 Pandas 对学生数据进行可视化。假设我们有一组学生数据,包括学生的姓名、成绩、性别和年龄等信息。
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 创建一个示例数据集
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Henry'],
'Score': [85, 92, 78, 90, 88, 76, 95, 89],
'Gender': ['Female', 'Male', 'Male', 'Male', 'Female', 'Male', 'Female', 'Male'],
'Age': [18, 19, 20, 21, 18, 19, 20, 21]
}
df = pd.DataFrame(data)
# 使用 Seaborn 和 Matplotlib 进行可视化
sns.set(style="whitegrid") # 设置 Seaborn 的样式
# 可视化 1: 学生成绩分布图 (直方图)
plt.figure(figsize=(8, 6))
sns.histplot(df['Score'], bins=10, kde=True, color='blue')
plt.title('Distribution of Student Scores', fontsize=16)
plt.xlabel('Score', fontsize=14)
plt.ylabel('Frequency', fontsize=14)
plt.show()
# 可视化 2: 按性别分组的平均成绩条形图
gender_scores = df.groupby('Gender')['Score'].mean().reset_index()
plt.figure(figsize=(8, 6))
sns.barplot(x='Gender', y='Score', data=gender_scores, palette='viridis')
plt.title('Average Scores by Gender', fontsize=16)
plt.xlabel('Gender', fontsize=14)
plt.ylabel('Average Score', fontsize=14)
plt.show()
# 可视化 3: 年龄与成绩的关系 (散点图)
plt.figure(figsize=(8, 6))
sns.scatterplot(x='Age', y='Score', hue='Gender', data=df, palette='Set1', s=100)
plt.title('Relationship between Age and Score', fontsize=16)
plt.xlabel('Age', fontsize=14)
plt.ylabel('Score', fontsize=14)
plt.legend(title='Gender')
plt.show()
# 可视化 4: 成绩的相关性热力图
correlation_matrix = df[['Score', 'Age']].corr()
plt.figure(figsize=(6, 4))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt='.2f')
plt.title('Correlation Matrix of Scores and Age', fontsize=14)
plt.show()
```
### 说明
上述代码展示了如何使用 Pandas 创建数据集,并通过 Matplotlib 和 Seaborn 提供多种类型的可视化图表:
- **直方图**:用于展示学生成绩的分布情况[^3]。
- **条形图**:用于比较不同性别学生的平均成绩[^1]。
- **散点图**:用于分析年龄与成绩之间的关系[^2]。
- **热力图**:用于显示成绩与年龄之间的相关性[^3]。
阅读全文
相关推荐










