甲、乙两个班各有40名学生,期末统计学考试成绩分布存于文件“习题3.4.xlsx”中:有”考试成绩“、”甲班人数“、”乙班人数“三列,考试成绩包括优、良、中、及格、不及格五个等级,根据文件中的数据,用R语言绘制两个班考试成绩的对比条形图和环形图
时间: 2024-01-22 14:02:22 浏览: 117
#加载所需库
library(readxl)
library(ggplot2)
library(dplyr)
#读取数据
data <- read_excel("习题3.4.xlsx")
#计算每个等级的总人数
data_new <- data %>%
group_by(考试成绩) %>%
summarize(甲班人数 = sum(甲班人数), 乙班人数 = sum(乙班人数))
#绘制对比条形图
ggplot(data_new, aes(x = 考试成绩)) +
geom_bar(aes(y = 甲班人数, fill = "甲班"), stat = "identity", position = "dodge") +
geom_bar(aes(y = -乙班人数, fill = "乙班"), stat = "identity", position = "dodge") +
scale_fill_manual(values = c("甲班" = "steelblue", "乙班" = "orange")) +
theme_minimal() +
labs(x = "考试成绩", y = "人数", title = "甲、乙两个班成绩对比条形图") +
coord_flip()
#绘制环形图
data_new$总人数 <- data_new$甲班人数 + data_new$乙班人数
data_new$比例 <- data_new$总人数 / sum(data_new$总人数)
ggplot(data_new, aes(x = "", y = 比例, fill = 考试成绩)) +
geom_bar(stat = "identity", width = 1, color = "white") +
coord_polar("y", start = 0) +
theme_void() +
theme(legend.position = "bottom") +
labs(title = "甲、乙两个班成绩对比环形图") +
scale_fill_manual(values = c("优" = "#4daf4a", "良" = "#377eb8", "中" = "#e41a1c", "及格" = "#984ea3", "不及格" = "#ff7f00")) +
guides(fill = guide_legend(title = "考试成绩"))
阅读全文