Skip to content

Instantly share code, notes, and snippets.

@bayesball
Last active January 2, 2016 10:59
Show Gist options
  • Save bayesball/8293777 to your computer and use it in GitHub Desktop.
Save bayesball/8293777 to your computer and use it in GitHub Desktop.
Shiny application to graph the average number of offensive events (H, HR, SO, etc) per game per team over the history of Major League Baseball.
library(shiny)
library(Lahman)
library(ggplot2)
# Define server logic required to plot various variables against year
shinyServer(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() +
geom_smooth(size=2, color="red", method="loess",
span=input$decimal) +
xlab("YEAR") + ylab("RATE PER GAME PER TEAM")
)
}, width=600, height=500)
})
library(shiny)
# Define UI for miles per gallon application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Offensive Production in Baseball History"),
# Sidebar with controls to select the variable to plot against mpg
# and to specify whether outliers should be included
sidebarPanel(
selectInput("variable", "Variable:",
list("Runs" = "R",
"Hits" = "H",
"Home Runs" = "HR",
"Doubles" = "X2B",
"Triples" = "X3B",
"Walks" = "BB",
"Strikeouts" = "SO",
"Stolen Bases" = "SB",
"Errors" = "E")),
sliderInput("range", "Range:",
min = 1901, max = 2012, format="###",
value = c(1901, 2012), 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")
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment