Last active
May 2, 2016 11:19
-
-
Save bayesball/423e41ed31deef57e863df33b969b8cf to your computer and use it in GitHub Desktop.
R Code to Visualize all of the In-Play Events During a Single Day of MLB Baseball
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: the openWAR and ggplot2 packages need to be installed | |
library(openWAR) | |
library(ggplot2) | |
ds <- getData(start = '2016-04-29', end = '2016-04-29') | |
ds$event <- as.character(ds$event) | |
ds$stand <- ifelse(ds$stand=="R", "Right-Handed Batter", | |
"Left-Handed Batter") | |
ds$Event <- with(ds, ifelse(event=="Double" | event=="Home Run" | | |
event=="Single" | event=="Triple", | |
event, "Out")) | |
diamond <- data.frame(x=c(0, -127.28 / 2, 0, 127.28 / 2, 0), | |
y=c(0, 127.28 / 2, 127.28, 127.28 / 2, 0)) | |
fouline1 <- data.frame(x=c(-127.28 / 2, -300), | |
y=c(127.28 / 2, 300)) | |
fouline2 <- data.frame(x=c(127.28 / 2, 300), | |
y=c(127.28 / 2, 300)) | |
fence <- data.frame(x=seq(-300, 300, length.out=100), | |
y=400 - .0011 * | |
seq(-300, 300, length.out=100) ^ 2 ) | |
ds$Event <- factor(ds$Event, | |
levels=c("Home Run", "Triple", "Double", "Single", "Out"), | |
ordered = TRUE) | |
plot <- ggplot(ds, aes(our.x, our.y, color=Event)) + | |
facet_wrap(~ stand, ncol=1) + | |
geom_point() + | |
geom_path(aes(x, y), data=diamond, lwd=.5, col="blue") + | |
geom_path(aes(x, y), data=fouline1, lwd=.5, col="blue") + | |
geom_path(aes(x, y), data=fouline2, lwd=.5, col="blue") + | |
geom_path(aes(x, y), data=fence, lwd=.5, col="blue") + | |
coord_fixed(ratio=1) + | |
scale_color_brewer(palette="Set1") + | |
xlab("") + ylab("") + | |
ggtitle("Locations of All Balls In-Play on April 29, 2016") + | |
scale_y_continuous(breaks=NULL) + | |
scale_x_continuous(breaks=NULL) | |
print(plot) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment