Search code examples
rplotshinyggvis

Delete ggvis plots from shiny


I have multiple ggvis plots in Shiny. I need to provide an action button, if the button is clicked all the plots need to be deleted.

Below is a sample code for ui.R and server.R:

ui.R

library(ggvis)
library(shiny)

shinyUI(fluidPage(
  titlePanel("Plotting slopes"),

  sidebarLayout(
  sidebarPanel(
  selectInput("segment", label = "Choose segment", choices = c("K 1", "K 2")),
  actionButton("abutton","Delete plots")),

mainPanel(ggvisOutput("plot"), ggvisOutput("plot2"))
)
))

server.R

library(shiny)
library(ggvis)

mtcars$cyl = factor(mtcars$cyl)
df1 = subset(mtcars, am == 0)
df2 = subset(mtcars, am == 1)

shinyServer(function(input, output) {
dataInput = reactive({
switch(input$segment,
       "K 1" = df1,
       "K 2" = df2)
})


values = function(x){
if(is.null(x)) return(NULL)
dat = dataInput()
row = dat[dat$cyl %in% unique(x$cyl), ]
paste0("Ave Weight: ", mean(row$wt),"<br />",
       "Ave Carb: ", mean(row$carb), "<br />")
}


vis1 = reactive({
dat = dataInput()
dat %>%
  group_by(cyl) %>%
  ggvis(~mpg, ~wt)  %>%
  layer_paths(stroke = ~cyl, strokeOpacity := 0.3, 
              strokeWidth := 5) %>%
  add_tooltip(values, "hover")
 })
  vis1 %>% bind_shiny("plot")

 vis2 = reactive({
dat = dataInput()
dat %>%
  group_by(cyl) %>%
  ggvis(~mpg, ~wt)  %>%
  layer_paths(stroke = ~cyl, strokeOpacity := 0.3, 
              strokeWidth := 5) %>%
  add_tooltip(values, "hover")
  })
  vis2 %>% bind_shiny("plot2")

})

Screenshot of the current output: screenshot


Solution

  • If you tolerate the plots NOT deleted but LOOK LIKE deleted, I think it'll be easy to give bind_shiny() a blank graph.

    server.R

      :
      vis2 %>% bind_shiny("plot2")    # the same up to here
      
      vis3 = mtcars %>%                   # preparation of a blank graph
        ggvis(~mpg, ~wt, opacity := 0) %>%
        layer_points() %>%
        hide_axis("x") %>%
        hide_axis("y")
      
      observeEvent(input$abutton, {    # When the button is clicked,
        bind_shiny(vis3, "plot")       # bind_shiny() reads and outputs a blank graph, vis3.
        bind_shiny(vis3, "plot2")      # When other Input is done, vis1 and vis2 return.
      }) 
      
    })