Skip to content

Instantly share code, notes, and snippets.

@bayesball
Last active February 5, 2021 12:51
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/5fea123c55bf61cf7e8d0a9dcbcccea1 to your computer and use it in GitHub Desktop.
Save bayesball/5fea123c55bf61cf7e8d0a9dcbcccea1 to your computer and use it in GitHub Desktop.
Shiny app to illustrate brushing to obtain in-play batting averages
library(shiny)
library(ggplot2)
library(dplyr)
sc2019_ip <- read.table("https://raw.githubusercontent.com/bayesball/CalledStrike/master/data/sc2019_ip.txt",
header = TRUE)
ui <- fluidPage(
h2("Brushing In-Play Batting Averages"),
textInput("name", "Batter Name:", value = ""),
plotOutput("plot", brush = "plot_brush"),
tableOutput("data")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
add_zone <- function(){
topKzone <- 3.5
botKzone <- 1.6
inKzone <- -0.85
outKzone <- 0.85
kZone <- data.frame(
x=c(inKzone, inKzone, outKzone, outKzone, inKzone),
y=c(botKzone, topKzone, topKzone, botKzone, botKzone)
)
geom_path(aes(.data$x, .data$y),
data=kZone, lwd = 1)
}
ggplot() +
geom_point(data = filter(sc2019_ip,
player_name == input$name),
aes(plate_x, plate_z, color = H)) +
add_zone() +
ggtitle(input$name) +
coord_equal()
}, res = 96)
output$data <- renderTable({
req(input$plot_brush)
sc1 <- brushedPoints(filter(sc2019_ip,
player_name == input$name),
input$plot_brush)
data.frame(Name = input$name,
xlo = min(sc1$plate_x),
xhi = max(sc1$plate_x),
zlo = min(sc1$plate_z),
zhi = max(sc1$plate_z),
AB = nrow(sc1),
H = sum(sc1$H),
BABIP = sum(sc1$H) / nrow(sc1))
}, digits = 3, width = '75%')
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment