library(ggplot2)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# Load data
sp <- read.csv(file = "StudentsPerformance.csv", stringsAsFactors = TRUE)
# View the structure of the data
str(sp)
## 'data.frame': 1000 obs. of 8 variables:
## $ gender : Factor w/ 2 levels "female","male": 1 1 1 2 2 1 1 2 2 1 ...
## $ race.ethnicity : Factor w/ 5 levels "group A","group B",..: 2 3 2 1 3 2 2 2 4 2 ...
## $ parental.level.of.education: Factor w/ 6 levels "associate's degree",..: 2 5 4 1 5 1 5 5 3 3 ...
## $ lunch : Factor w/ 2 levels "free/reduced",..: 2 2 2 1 2 2 2 1 1 1 ...
## $ test.preparation.course : Factor w/ 2 levels "completed","none": 2 1 2 2 2 2 1 2 1 2 ...
## $ math.score : int 72 69 90 47 76 71 88 40 64 38 ...
## $ reading.score : int 72 90 95 57 78 83 95 43 64 60 ...
## $ writing.score : int 74 88 93 44 75 78 92 39 67 50 ...
# Plot 1: Math score vs Writing score, colored by lunch type
ggplot(sp, aes(x= math.score, y= writing.score, color = lunch)) +
geom_point()

# Calculate the correlation between math and reading scores
math_reading_cor <- cor(sp$math.score, sp$reading.score)
math_reading_cor
## [1] 0.8175797
# Plot 2: Average math score by lunch type
sp %>%
group_by(lunch) %>%
summarise(math = mean(math.score)) %>%
ggplot(aes(x= lunch, y= math, fill = lunch)) +
geom_col()

# Group by parental level of education and calculate average math score
sp1 <- sp %>%
group_by(parental.level.of.education) %>%
summarise(math = round(mean(math.score))) %>%
arrange(desc(math))
# Reorder the factor levels for parental education
sp1$parental.level.of.education <- factor(sp1$parental.level.of.education,
levels = sp1$parental.level.of.education[order(sp1$math,decreasing = TRUE)])
# Plot 3: Average math score by parental level of education
ggplot(sp1, aes(x = parental.level.of.education, y= math, fill = parental.level.of.education)) +
geom_col() +
geom_text(aes(label = math, vjust = -0.8, hjust = 0.5, color = parental.level.of.education)) +
ylim(min(sp1$math, 0)*1.1, max(sp1$math)*1.1)

# Plot 4: Hide legend for parental education plot
ggplot(sp1, aes(x = parental.level.of.education, y= math, fill = parental.level.of.education)) +
geom_col(show.legend=F) +
geom_text(aes(label = math, vjust = -0.8, hjust = 0.5, color = parental.level.of.education), show.legend=F) +
ylim(min(sp1$math, 0)*1.1, max(sp1$math)*1.1)

# Plot 5: Gender vs Writing score bar plot
ggplot(sp, aes( x= gender, y = writing.score, fill = gender)) +
geom_col() +
labs(x = "Gender", y = "Writing Score") +
theme_minimal()

# Plot 6: Gender vs Writing score box plot
ggplot(sp, aes( x= gender, y = writing.score, fill = gender)) +
geom_boxplot() +
labs(x = "Gender", y = "Writing Score") +
theme_minimal()
