Search code examples
rshiny

Downloading Shiny Plot as PNG


I am trying to learn shiny and am working on a simple app that creates a plot for you and lets you download it. Here is the code:

library(shiny)
library(shinycssloaders)
library(ambient)

ui <- fluidPage(
  sliderInput("min","Grid Minimum",min = 5, max = 15,value = 10),
  sliderInput("max","Grid Maximum",min = 5, max = 15,value = 10),
  sliderInput("lenght","Grid Breaks",min = 100, max = 1000, step = 100, value = 500),
  plotOutput("worleyplot"),
  downloadButton("dl","Download Pic")
)

server <- function(input,output){
  preview <- function(){
    grid <- long_grid(seq(input$min,input$max,length.out = input$lenght),
                      seq(input$min,input$max,length.out = input$lenght))
    grid$noise <- gen_worley(grid$x,grid$y,value = 'distance')
    plot(grid,noise)
  } 
  
output$worleyplot <- renderPlot(preview())
output$dl <- downloadHandler(
  filename <- "plot.png",
  content <- function(file){
    png(file)
    plotInput()
    dev.off
  }
)
}
shinyApp(ui, server)

But when I click the download button, it doesn't prompt me to save a png file and instead shows a htm file which doesn't even download when I click save.


Solution

  • Here is your corrected server side code:

    server <- function(input,output){
      preview <- function(){
        grid <- long_grid(seq(input$min,input$max,length.out = input$lenght),
                          seq(input$min,input$max,length.out = input$lenght))
        grid$noise <- gen_worley(grid$x,grid$y,value = 'distance')
        plot(grid,noise)
      } 
      
      output$worleyplot <- renderPlot(preview())
      output$dl <- downloadHandler(
        filename = "plot.png",
        content = function(file){
          png(file)
          preview()
          dev.off()
        }
      )
    }
    

    First of all, you passed a non-existent function, plotInput(), to downloadHandler(content =). I replaced that with the function that rightly generates the plot, preview().

    Secondly, dev.off() was missing its brackets. With these corrections, you can now generate plots and download them as .png files.