Skip to content

Instantly share code, notes, and snippets.

@bayesball
Created October 31, 2018 11:23
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/59386ccc463fcb24d722c027a526e0bd to your computer and use it in GitHub Desktop.
Save bayesball/59386ccc463fcb24d722c027a526e0bd to your computer and use it in GitHub Desktop.
Shiny app for displaying baseball history
library(shiny)
# Define UI for application that draws a histogram
ui <- shinyUI(pageWithSidebar(
# Application title
headerPanel("Offensive Production in Baseball History"),
# Sidebar with controls to select the variable to plot against year
# also choose plotting and smooth colors, range of years, and smoothing width
sidebarPanel(
selectInput("variable", "Variable:",
c("Runs" = "R",
"Hits" = "H",
"Home Runs" = "HR",
"Doubles" = "X2B",
"Triples" = "X3B",
"Walks" = "BB",
"Strikeouts" = "SO",
"Stolen Bases" = "SB",
"Errors" = "E")),
selectInput("pcolor", "Points Color:",
c("Blue" = "blue", "Red" = "red", "Green" = "green",
"Orange" = "orange", "Black" = "black", "Yellow" = "yellow")),
selectInput("scolor", "Smooth Color:",
c("Red" = "red", "Blue" = "blue", "Green" = "green",
"Orange" = "orange", "Black" = "black", "Yellow" = "yellow")),
sliderInput("salpha", "Alpha:",
min = 0, max = 1,
value = 0.5, step = 0.05),
sliderInput("range", "Range:",
min = 1901, max = 2016, sep = "",
value = c(1901, 2016), step = 1),
sliderInput("decimal", "Loess Smoothing Fraction:",
min = 0.05, max = 0.95, value = 0.2, step= 0.05)
),
# Show the caption and plot of the requested variable against mpg
mainPanel(
h3(textOutput("caption")),
plotOutput("mpgPlot")
)
))
library(Lahman)
library(ggplot2)
# Define server logic required to draw a histogram
server <- function(input, output) {
# Compute the forumla text in a reactive function since it is
# shared by the output$caption and output$mpgPlot functions
formulaText <- reactive({
paste("Variable:", input$variable,
"Per Game Per Team:",
input$range[1], "to", input$range[2])
})
# Return the formula text for printing as a caption
output$caption <- renderText({
formulaText()
})
# Generate a plot of the requested variable against mpg and only
# include outliers if requested
output$mpgPlot <- renderPlot({
Teams.recent <- subset(Teams, yearID >= input$range[1] &
yearID <= input$range[2])
Teams.recent$stat.game <- Teams.recent[, input$variable] / Teams.recent[, "G"]
print(ggplot(Teams.recent, aes(yearID, stat.game)) +
geom_point(color = input$pcolor, alpha = input$salpha) +
geom_smooth(size=2, color=input$scolor, method="loess",
span=input$decimal) +
xlab("YEAR") + ylab("RATE PER GAME PER TEAM") +
theme(text = element_text(size=20))
)
}, width=600, height=500)
}
# Run the application
shinyApp(ui = ui, server = server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment