1

I have been trying to download the plotout while using eventReactive in R shiny. Below is the example code

library(shiny)

server <- function(input, output) {

  getplot = eventReactive(input$plot,{



plot(iris[,1])
  })
  output$plot = renderPlot({
   getplot()
  })
  output$downloadplot <- downloadHandler(filename ="test.png",
                                         content = function(file) {
                                           png(file)
                                         getplot()
                                           dev.off()
                                         },
                                         contentType = "image/png")
}

ui <- fluidPage(
  actionButton("plot","test plot"),
  plotOutput("plot"),
  downloadButton("downloadplot", label = "Save png")

)

shinyApp(ui = ui, server = server)

Can any one help what must be changed inorder to successfuly download the file? ( currently it says file not found) p.s: I have tried using thecouter as mentioned in this R Shiny eventReactive actionBotton interaction still no success

Community
  • 1
  • 1
  • According to [this](http://stackoverflow.com/a/24569468/5894457) opening it in web browser instead of preview pane solves the problem. – SBista Jan 02 '17 at 13:12

1 Answers1

0

The problem with your code is that you use eventReactive for plotting function and it acts only in response to actionButton "test plot". Hereby, there can be no plot produced after you click "Save png" button, as you don't click "test plot" at the same time. Watch out:

  1. You give the same inputId twice in your ui function ("plot" x2)
  2. You do something not recommended to make plotting occur after clicking the button. The better way is described here: https://shiny.rstudio.com/articles/isolation.html

This version should work both in browser and viewer pane:

library(shiny)

server <- function(input, output) {

  getplot = function() {plot(iris[,1])} # plotting function independent from any button

  output$plot = renderPlot({
    # no plot displayed if "test plot" button hasn't been clicked
    if (input$plotButton[[1]] == 0) # this value turns to 1 when button is clicked
      return() 
    getplot()
    })

  output$downloadplot <- downloadHandler(filename ="test.png",
                                         content = function(file) {
                                           png(file)
                                           getplot() # simple, independent function
                                           dev.off()
                                           },
                                         contentType = "image/png")
  }

ui <- fluidPage(
  actionButton("plotButton", "test plot"),
  plotOutput("plot"),
  downloadButton("downloadplot", label = "Save png")
)

shinyApp(ui = ui, server = server)

I hope this helps