Home:ALL Converter>Saving user generated ggplot from Shiny App

Saving user generated ggplot from Shiny App

Ask Time:2021-01-13T04:48:24         Author:Jennifer

Json Formatter

I am trying to create a Shiny Web App with a ggplot and include a feature to download the generated plot. Here are my UI and Server files respectively.

SERVER

shinyServer(function(input, output, session) {
  
  vals <- reactiveValues()
  
    output$Plot <- renderPlot({
      gg <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
      vals$gg <- gg
      
      print(gg)
    }, height = function() {
      session$clientData$output_BehPlot_width
    } )
    
    # downloadHandler contains 2 arguments as functions, namely filename, content
    output$down <- downloadHandler(
      filename =  function() {
        paste("behavior", input$var3, sep=".")
      },
      # content is a function with argument file. content writes the plot to the device
      content = function(filename) {
        if(input$var3 == "png"){
          png(filename) # open the png device
          #ggsave(vals$gg)
          print(vals$gg) # for GGPLOT
          dev.off()  # turn the device off
          }
        else {
          #ggsave(vals$gg)
          pdf(filename) # open the pdf device
        print(vals$gg) # for GGPLOT
        dev.off()  # turn the device off
        }
      } 
    )


    
})

UI

shinyUI(fluidPage(
  
  # Application title
  titlePanel("TEST SHINY"),
  
  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      radioButtons(inputId = "var3", label = "Select the file type", choices = list("png", "pdf")),
      
      downloadButton("downloadPlot", "Download")
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("Plot", height="auto", width = "auto")
    )
  )
))

This is built from the consultation of several prior Stack Overflow threads and Github gists. (such as this one: R Shiny saving reactive ggplots)

When I run the download feature in a test session in my R console and browser, the result is an HTML file that does not print the plot. Is there something that I am missing?

Thank you!

Author:Jennifer,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65691821/saving-user-generated-ggplot-from-shiny-app
yy