Skip to content

Instantly share code, notes, and snippets.

@Ram-N
Created April 18, 2016 04:30
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 Ram-N/49f6e625f8b725629a1555ce91a2ed4f to your computer and use it in GitHub Desktop.
Save Ram-N/49f6e625f8b725629a1555ce91a2ed4f to your computer and use it in GitHub Desktop.
An example of using ggVis selectize with multiple=TRUE in Shiny.
library(ggvis)
library(shiny)
#Example of Selectize, with Multiple = TRUE
ui = shinyUI(pageWithSidebar(
div(),
sidebarPanel(
sliderInput("n", "Number of points", min = 1, max = nrow(mtcars),
value = 10, step = 1),
selectizeInput(
'e2', 'Select Num Cylinders', choices = c(4,6,8), multiple = TRUE
),
textOutput("ex_out")
),
mainPanel(
ggvisOutput("plot"),
tableOutput("mtc_table")
)
))
server = shinyServer(function(input, output, session) {
#This is done to fix the colors for each level
mtcars$cyl<-factor(mtcars$cyl, levels=c(4,6,8))
# A reactive subset of mtcars
mtc <- reactive({
mtcars %>% filter(cyl %in% as.integer(input$e2))
})
output$ex_out <- renderPrint({as.integer(input$e2) })
# A simple visualisation. In shiny apps, need to register observers
# and tell shiny where to put the controls
mtc %>%
ggvis(~wt, fill = ~cyl) %>%
group_by(cyl) %>%
layer_densities() %>%
bind_shiny("plot", "plot_ui")
output$mtc_table <- renderTable({
#Make the reactives wait until the minimum needed inputs have
#been entered.
validate(
need(input$e2, 'Please select at least one group')
)
mtc()[]
})
})
shinyApp(ui = ui, server = server)
### Second example, showing how validate and need can be used.
## This example is from Stack OVerflow. The idea of validate and need() is clearly illustrated
library(shiny)
library(ggplot2)
myData <- data.frame(group = sample(letters[1:4], 100, TRUE)
, cohort = sample(0:4, 100, TRUE)
, value = runif(100))
runApp(
list(ui = fluidPage(
column(4,
checkboxGroupInput('group', 'Pick a group', choices = letters[1:4]),
selectizeInput('cohort', 'Pick a cohort', choices = 0:4)),
column(8, plotOutput('myplot'))
)
, server = function(input, output, session) {
appData <- reactive({
myData[myData$group %in% input$group & myData$cohort == input$cohort,]
})
output$myplot <- renderPlot({
validate(
need(input$group, 'Please select at least one group'),
need(input$cohort > 0, 'Please choose a cohort greater than zero')
)
g <-ggplot(appData(),aes(x=group, y=value)) +
stat_summary(fun.y=sum, geom="bar") +
ggtitle(paste('cohort', input$cohort))
g
})
}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment