Load libraries

library(tidyverse)
library(gganimate)
library(gifski)

Lab Exercise 1

Add the data of New Jersey (including a new annotation) to the same plot so that the graph shows evolution of college tuition in New York and New Jersey in the same plot.

read_csv("Datasets/us_avg_tuition.csv") -> tuition_data

tuition_data <- tuition_data %>%
  pivot_longer(cols = 2:13, names_to = "year", values_to = "tuition") %>%
  mutate(tuition = parse_number(tuition)) %>%
  tidyr::extract(year, into = "year", "^(....)") %>%
  mutate(year = as.numeric(year))

ny_data <- filter(tuition_data, (State == "New York") | (State == "New Jersey"))

ggplot(ny_data, aes(x = year, y = tuition, color = State, group = State)) + 
  geom_line() + 
  geom_point() +
  annotate("text", label = "New York", x = 2004.5, y = ny_data[ny_data$State == "New York",][[1, 3]] + 250) + 
  annotate("text", label = "New Jersey", x = 2004.5, y = ny_data[[1,3]] - 250) +
  labs(x = "Year", y = "Average tuition (in USD)", title = "College Tuition in New York State") + 
  xlim(2003.5, 2015.5) + theme(plot.title = element_text(hjust = 0.5)) + 
  scale_x_continuous(breaks = seq(2004, 2015, by = 1)) +
  transition_reveal(year)

Lab Exercise 2

order <- tuition_data %>%
  filter(year == 2015)

fct_reorder(as.factor(unique(tuition_data$State)), order$tuition) -> temp

ggplot(tuition_data, aes(x = tuition, y = fct_relevel(as.factor(State), levels(temp)), color = State)) +
  geom_bar(stat = "identity", fill = "black") +
  theme(legend.position = "none") +
  transition_time(year)

Lab Exercise 3

ggplot(diamonds, aes(x = carat, y = price)) + 
  geom_point(aes(color = color)) +
  geom_smooth() +
  labs(title = "Cut quality:{cut}", x = "Carat", y = "Price (USD)") +
  theme(plot.title = element_text(hjust = 0.5)) + 
  enter_fade() + exit_shrink() + 
  transition_states(cut) -> anime

animate(anime, fps = 5, res = 100)