Skip to content

Instantly share code, notes, and snippets.

@cryoguy
Created November 12, 2016 22:24
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 cryoguy/92a4affeead17563df15d55b630a214d to your computer and use it in GitHub Desktop.
Save cryoguy/92a4affeead17563df15d55b630a214d to your computer and use it in GitHub Desktop.
R Shiny Stuff
library("shiny")
library("datasets")
library("ggplot2")
#from here http://web.stanford.edu/~cengel/cgi-bin/anthrospace/building-my-first-shiny-application-with-ggplot
# We tweak the "am" field to have nicer factor labels. Since this doesn't
# rely on any user inputs we can do this once at startup and then use the
# value throughout the lifetime of the application
mpgData <- mtcars
mpgData$am <- factor(mpgData$am, labels = c("Automatic", "Manual"))
# Define server logic required to plot various variables against mpg
shinyServer(function(input, output) {
# Compute the forumla text in a reactive expression since it is
# shared by the output$caption and output$mpgPlot expressions
formulaText <- reactive({
paste("mpg ~", input$variable)
})
# 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
# ggplot version
output$mpgPlot <- renderPlot({
# check for the input variable
if (input$variable == "am") {
# am
mpgData <- data.frame(mpg = mtcars$mpg, var = factor(mtcars[[input$variable]], labels = c("Automatic", "Manual")))
}
else {
# cyl and gear
mpgData <- data.frame(mpg = mtcars$mpg, var = factor(mtcars[[input$variable]]))
}
p <- ggplot(mpgData, aes(var, mpg)) +
geom_boxplot(outlier.size = ifelse(input$outliers, 2, NA)) +
xlab(input$variable)
print(p)
})
})
library(shiny)
# Define UI for miles per gallon application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Miles Per Gallon"),
# Sidebar with controls to select the variable to plot against mpg
# and to specify whether outliers should be included
sidebarPanel(
selectInput("variable", "Variable:",
list("Cylinders" = "cyl",
"Transmission" = "am",
"Gears" = "gear")),
checkboxInput("outliers", "Show outliers", FALSE)
),
# 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