Lab Homework 17

knitr::opts_chunk$set(fig.align="center",message=F,warning=F,cache=T)
library(sf)           
library(ggplot2)      
library(dplyr)        
library(tidyr)        
library(scales)       
library(RColorBrewer) 
library(units)
library(cowplot)
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("../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))

df <- filter(tuition_data, State %in% c("New York", "New Jersey"))
ny_data <- filter(tuition_data, State == "New York")
nj_data <- filter(tuition_data, State == "New Jersey")


ggplot(df, aes(x = year, y = tuition, color = State, group = State)) + 
  geom_line() + 
  geom_point() +
  annotate("text", label = "New York", x = 2004.5, y = ny_data[[1,3]] + 60) + 
  annotate("text", label = "New Jersey", x = 2004.5, y = nj_data[[1,3]] + 60) + 
  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

Try to reproduce the following graph:

ggplot(tuition_data, aes(x = tuition, y = State, color = State, group = State)) + 
  geom_bar(stat = "identity") +
  labs(x = "Tuition (USD)", y = "State", title = "Year: {frame_time}") +
  theme(legend.position="none", plot.title=element_text(hjust=0.5)) +
  transition_time(year) +
  ease_aes('linear') -> p

animate(p, duration = 6, fps = 2)

Lab Exercise 3

Try to reproduce the following graph with the diamonds data set:

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

animate(p2, fps=10, duration = 15)