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

Lab Exercise

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("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_nj_data <- filter(tuition_data, State %in% c("New York", "New Jersey"))

ny_2004_tuition <- filter(ny_nj_data, State == "New York", year == 2004)[["tuition"]]
nj_2004_tuition <- filter(ny_nj_data, State == "New Jersey", year == 2004)[["tuition"]]

ggplot(ny_nj_data, aes(x = year, y = tuition, color = State, group = State)) +
  geom_line() +
  geom_point() +
  annotate("text", label = "New York", x = 2004.5, y = ny_2004_tuition + 60, color = "red") +
  annotate("text", label = "New Jersey", x = 2004.5, y = nj_2004_tuition - 60, color = "blue") +
  labs(
    title = "College Tuition in New York and New Jersey",
    x = "Year",
    y = "Average Tuition (in USD)"
  ) +
  transition_reveal(year)

Lab Exercise

Try to reproduce the following graph:

p <- ggplot(tuition_data, aes(x = tuition, y = fct_reorder(State, tuition), fill = State)) +
  geom_col(show.legend = F) +
  labs(
    title = "Year: {closest_state}",
    x = "tuition (in USD)",
    y = "State"
  ) +
  theme(plot.title = element_text(hjust = 0.5)) +
  transition_states(year, transition_length = 1, state_length = 1) +
  ease_aes('linear')

animate(p, duration = 15, fps = 4)

Lab Exercise

Try to reproduce the following graph with the diamonds data set

p1 <- ggplot(diamonds, aes(x = carat, y = price, color = color)) +
  geom_point(alpha = 0.7) +
  geom_smooth(color = "blue") +
  labs(
    title = "Cut Quality: {closest_state}",
    x = "Carat",
    y = "Price (USD)"
  ) +
  enter_fade() + exit_shrink() + 
  theme(plot.title = element_text(hjust = 0.5)) +
  transition_states(cut, transition_length = 2, state_length = 1)

animate(p1, duration = 10, fps = 5, renderer = gifski_renderer())