Skip to content

Instantly share code, notes, and snippets.

@bayesball
Created January 3, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bayesball/6afd88ed3e48fd62b7b6 to your computer and use it in GitHub Desktop.
Save bayesball/6afd88ed3e48fd62b7b6 to your computer and use it in GitHub Desktop.
R function to plot the components of a batting average
plot.batting.average <- function(name, season){
require(Lahman)
require(dplyr)
Name <- unlist(strsplit(name, split=" "))
id <- subset(Master, nameFirst==Name[1] &
nameLast==Name[2])$playerID[1]
data <- subset(Batting, playerID==id & yearID==season)
data <- summarize(data, H=sum(H), AB=sum(AB),
SO=sum(SO), HR=sum(HR))
so.rate <- with(data, SO / AB)
hr.rate <- with(data, HR / (AB - SO))
hit.rate <- with(data, (H - HR) / (AB - SO - HR))
AVG <- with(data, H / AB)
plot(1, 1, xlim=c(-0.3, 1.3), ylim=c(-0.3, 1.3), type="n",
axes=FALSE, asp=1, xlab="", ylab="",
main=paste(season, name))
rect(0, 0, 1, 1)
lines(so.rate * c(1, 1), c(0, 1))
lines(c(so.rate, 1), hr.rate * c(1, 1))
lines(so.rate + (1 - so.rate) * hit.rate * c(1, 1),
c(hr.rate, 1))
rect(so.rate, 0, 1, hr.rate, col="red")
rect(so.rate, hr.rate,
so.rate + (1 - so.rate) * hit.rate, 1, col="blue")
text(so.rate/2, -.1, "SO")
text(-.1, hr.rate/2, "HR")
text(so.rate + hit.rate / 2, 1.1, "HIP")
t1 <- paste("AVG: ", round(AVG, 3), "=")
t2 <- as.character(round((1 - so.rate) * hr.rate, 3))
t3 <- "+"
t4 <- as.character(
round((1 - so.rate) * (1 - hr.rate) * hit.rate, 3))
cl <- c("black", "red", "black", "blue")
text(0.1 + c(.15, .55, .7, .85), 1.3, c(t1, t2, t3, t4),
col=cl, cex=1)
text(0.5, -0.21, "SO.RATE HR.RATE BABIP" )
text(0.5, -0.29, paste(round(so.rate, 3),
round(hr.rate, 3),
round(hit.rate, 3), sep=" "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment