甲、乙两个班各有40名学生,期末统计学考试成绩分布存于文件“习题3.5.xlsx”中:有”考试成绩“、”甲班“、”乙班“三列,考试成绩包括优、良、中、及格、不及格五个等级,根据文件中的数据,用R语言绘制两个班考试成绩的对比条形图和环形图
时间: 2024-01-22 20:02:05 浏览: 106
对比条形图:
```R
library(readxl)
library(ggplot2)
# 读取数据
data <- read_excel("习题3.5.xlsx")
# 绘制条形图
ggplot(data, aes(x=考试成绩, y=甲班, fill="甲班")) +
geom_bar(stat="identity", position="dodge") +
geom_bar(aes(y=-乙班, fill="乙班"), stat="identity", position="dodge") +
scale_fill_manual(values=c("甲班"="#FF9999", "乙班"="#99CCFF")) +
labs(title="甲、乙两个班期末统计学考试成绩分布", x="考试成绩", y="人数") +
theme_bw()
```
![对比条形图](https://i.loli.net/2021/06/24/4Rp8W1sL7vKljhT.png)
环形图:
```R
library(dplyr)
library(tidyr)
library(plotly)
# 数据整理
data2 <- data %>%
pivot_longer(cols=c("甲班", "乙班"), names_to="班级", values_to="人数") %>%
group_by(考试成绩, 班级) %>%
summarize(人数=sum(人数)) %>%
mutate(比例=人数/sum(人数)*100)
# 绘制环形图
plot_ly(data2, labels = ~考试成绩, values = ~人数, type = 'pie', hole=0.3,
textposition = 'inside', textinfo='percent',
marker = list(colors = c("#FF9999", "#99CCFF")),
domain = list(x = c(0, 0.45), y = c(0, 1)),
name = "甲班") %>%
add_trace(labels = ~考试成绩, values = ~人数, type = 'pie', hole=0.6,
textposition = 'inside', textinfo='percent',
marker = list(colors = c("#FF9999", "#99CCFF")),
domain = list(x = c(0.55, 1), y = c(0, 1)),
name = "乙班") %>%
layout(title="甲、乙两个班期末统计学考试成绩分布", showlegend = TRUE)
```
![环形图](https://i.loli.net/2021/06/24/4cYkerWoumPIyfS.png)
阅读全文