Skip to content

Instantly share code, notes, and snippets.

@bayesball
Created November 15, 2023 12:47
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/6c78f4d3ac8f613d36c9b737299e3bcb to your computer and use it in GitHub Desktop.
Save bayesball/6c78f4d3ac8f613d36c9b737299e3bcb to your computer and use it in GitHub Desktop.
Shiny app that uses the mlbplotR package to produce scatterplots with team logo points
# live version of Shiny app
# https://bayesball.shinyapps.io/fg2023_discipline/
library(shiny)
library(mlbplotR)
library(dplyr)
library(ggplot2)
library(readr)
# data work
fg <- read_csv("https://raw.githubusercontent.com/bayesball/HomeRuns2021/main/fg2023_plate_discipline.csv")
teams <- read_csv("https://raw.githubusercontent.com/bayesball/HomeRuns2021/main/teams.csv")
sc <- read_csv("https://raw.githubusercontent.com/bayesball/HomeRuns2021/main/fg2023_statcast.csv")
names(sc)[c(8, 9, 10)] <-
c("Barrel_f", "HardHit", "HardHit_f")
fg_sc <- inner_join(fg, sc, by = "Team")
fg_sc <- inner_join(fg_sc, teams,
by = "Team")
varlist <- names(fg_sc)[c(2:12, 15, 17, 18,
19, 20, 21, 22, 24, 26)]
# plotting function
myplot <- function(x_var, y_var, league){
if(league == "NL"){
fg_sc <- filter(fg_sc, League == "NL")
}
if(league == "AL"){
fg_sc <- filter(fg_sc, League == "AL")
}
ggplot(data = fg_sc,
mapping = aes(.data[[x_var]], .data[[y_var]])) +
geom_mlb_scoreboard_logos(aes(team_abbr = Team_mlb),
width = 0.075) +
geom_smooth(method = "lm", formula = "y ~ x", se = FALSE) +
theme(text=element_text(size=18),
plot.title = element_text(colour = "blue", size = 16,
hjust = 0.5, vjust = 0.8, angle = 0)) +
ggtitle(paste("2023 FanGraphs Team Batting Data - ",
league))
}
# shiny user interface and server components
ui <- fluidPage(
theme = bslib::bs_theme(version = 4,
bootswatch = "superhero"),
fluidRow(
column(4, wellPanel(
h3("Exploring FanGraphs MLB Team Batting Data"),
hr(), hr(), hr(),
selectInput("xvar", "Select Horizontal Variable:",
varlist,
selected = "Swing"),
selectInput("yvar", "Select Vertical Variable:",
varlist,
selected = "Contact" ),
radioButtons(
"league",
"Select League:",
choices = c("NL", "AL", "All Teams"),
selected = "All Teams",
inline = FALSE,
)
)),
column(8,
hr(),
plotOutput("plot",
height = "500px",
width = "580px"),
hr(), hr(),
p("Data is collected from the Team Batting Stats section
from fangraphs.com."),
p("The mlbplotR package is used to
plot the MLB team logos in the ggplot scatterplot.")
))
)
server <- function(input, output, session) {
output$plot <- renderPlot({
myplot(input$xvar, input$yvar, input$league)
}, res = 96)
}
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment