Search code examples
shinyggvis

Toggle ggvis-layer with checkbox in a Shiny application


I want to add a checkbox that toggles the layers shown in a ggvis plot in a Shiny application.

library(shiny)
library(ggvis)

ui <- shinyUI(fluidPage(sidebarLayout(
   sidebarPanel(
   checkboxInput('loess','loess',TRUE)
  ),
   mainPanel(
   ggvisOutput("plot")
  )
 )))


server <- shinyServer(function(input, output) {

 mtcars %>%
    ggvis(~wt, ~mpg) %>%
    layer_points() %>%
     # if(input$loess) layer_smooths() %>%
    bind_shiny("plot", "plot_ui")
 })

shinyApp(ui = ui, server = server)

Is this possible to do in the ggvis pipeline using shiny the same gist as the commented line in the code above?


Solution

  • I don't think you can use the pipe directly for this. You also need to be in a reactive environment to access input$loess. You could do:

    observe({
            plot <- mtcars %>%
                    ggvis(~wt, ~mpg) %>%
                    layer_points()
            if(input$loess) plot <- plot %>% layer_smooths()
            plot %>% bind_shiny("plot", "plot_ui")
    })