用python写代码,5.利用数据2-5,画出两班的成绩对比条形图和环形图,画出雷达图,看看考试成绩的分布是否相似。2-5是 优有甲班3人,乙班6人,良是甲班6人,乙班15人,中是甲班18人,乙班9人,及格是甲班9人,乙班8人,不及格是甲班4人,乙班2人。
时间: 2024-05-22 10:16:52 浏览: 47
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
# 数据
data = {
'优': {
'甲班': 3,
'乙班': 6
},
'良': {
'甲班': 6,
'乙班': 15
},
'中': {
'甲班': 18,
'乙班': 9
},
'及格': {
'甲班': 9,
'乙班': 8
},
'不及格': {
'甲班': 4,
'乙班': 2
}
}
# 条形图
names = list(data.keys())
values1 = [data[name]['甲班'] for name in names]
values2 = [data[name]['乙班'] for name in names]
fig, ax = plt.subplots()
ax.bar(names, values1, label='甲班')
ax.bar(names, values2, bottom=values1, label='乙班')
ax.set_xlabel('成绩')
ax.set_ylabel('人数')
ax.set_title('成绩对比条形图')
ax.legend()
# 环形图
total1 = sum([data[name]['甲班'] for name in names])
total2 = sum([data[name]['乙班'] for name in names])
sizes = [total1, total2]
labels = ['甲班', '乙班']
colors = ['lightblue', 'lightgreen']
fig, ax = plt.subplots()
ax.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax.set_title('成绩占比环形图')
# 雷达图
angles = np.linspace(0, 2 * np.pi, len(names), endpoint=False)
angles = np.concatenate((angles, [angles[0]]))
values1_norm = [data[name]['甲班'] / total1 for name in names]
values2_norm = [data[name]['乙班'] / total2 for name in names]
values1_norm = np.concatenate((values1_norm, [values1_norm[0]]))
values2_norm = np.concatenate((values2_norm, [values2_norm[0]]))
fig, ax = plt.subplots(subplot_kw={'polar': True})
ax.plot(angles, values1_norm, 'o-', linewidth=2, label='甲班')
ax.fill(angles, values1_norm, alpha=0.25)
ax.plot(angles, values2_norm, 'o-', linewidth=2, label='乙班')
ax.fill(angles, values2_norm, alpha=0.25)
ax.set_thetagrids(angles * 180 / np.pi, names)
ax.set_title('成绩分布雷达图')
ax.legend()
plt.show()
阅读全文