Skip to content

Instantly share code, notes, and snippets.

@BillPetti
Created February 10, 2016 13:15
Show Gist options
  • Save BillPetti/ea350406bcfc4a30d406 to your computer and use it in GitHub Desktop.
Save BillPetti/ea350406bcfc4a30d406 to your computer and use it in GitHub Desktop.
Code used for creating an animated plot of cumulative WAR for players through their age-23 season
require(dplyr)
require(ggplot2)
require(gganimate)
war <- read.csv("https://raw.githubusercontent.com/BillPetti/General-Code-Reference/master/FanGraphs_Leaderboard_Cum_WAR.csv", header=TRUE, na.strings="NA", dec=".", stringsAsFactors = FALSE)
war <- war %>% group_by(playerid) %>% arrange(Age) %>% mutate(Cumulative.Off = cumsum(Off), Cumulative.Def = cumsum(Def), Cumulative.WAR = cumsum(WAR))
plot <- ggplot(war, aes(Cumulative.Off, Cumulative.Def, frame = Age)) + geom_point(data = filter(war, Name == "Ted Williams"), colour = "red4", aes(size = Cumulative.WAR)) + geom_text(data = filter(war, Name == "Ted Williams"), aes(label = paste0("Williams:\n", Cumulative.WAR)), fontface = 2, size = 4.5, hjust=1, vjust=-1) + geom_point(data = filter(war, Name == "Ken Griffey Jr."), colour = "cyan3", aes(size = Cumulative.WAR)) + geom_text(data = filter(war, Name == "Ken Griffey Jr."), aes(label = paste0("Griffey, Jr.:\n", Cumulative.WAR)), fontface = 2, size = 4.5, hjust=0.5, vjust=-1) + geom_point(data = filter(war, Name == "Mike Trout"), colour = "firebrick1", aes(size = Cumulative.WAR)) + geom_text(data = filter(war, Name == "Mike Trout"), aes(label = paste0("Trout:\n", Cumulative.WAR)), fontface = 2, size = 4.5, hjust=0.5, vjust=-1) + geom_point(data = filter(war, Age > 17), colour = "grey50", aes(size = Cumulative.WAR), alpha = .25) + ggtitle("Cumulative WAR by Age\nAge 18 -") + theme_bw() + theme(legend.position = "bottom", legend.title = element_text(face = "bold"), text = element_text(family = "Georgia"), plot.title = element_text(color = "black", face = "bold", size = 16)) + scale_size("Cumulative FanGraphs WAR") + xlab("Cumulative Offensive RAA") + ylab("Cumulative Defensive RAA")
plot
gg_animate(plot, "cum.WAR.gif", interval = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment