Shiny: use downloadHandler for a list of ggplot objects

Hello,

I have Shiny app with a reactive expression structured like this:

doStuff <- reactive({
  # Some code here
  output$downloadmyplots <- downloadHandler(
    # What to do here?
  )
})

The section "Some code here" produces an object x, which is a list of ggplot objects. The object downloadmyplots is a downloadButton in ui.R. I'd like to put the ggplot objects in x in a single PDF document, one plot per page, then let the user download it. How might I go about doing this?

Thanks!

Try something like the following.

library(shiny)
library(ggplot2)

# Define UI for application that draws a histogram
ui <- fluidPage(
  fluidRow(
    textInput("exportFile",
              "File name for download: ",
              value = "myjunk.pdf"),
    downloadButton("dl")
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  # Generate the plots.
  plots <- reactiveValues()
  plots$p1 <- ggplot(data = iris) + geom_point(mapping = aes(x = Petal.Length, y = Petal.Width))
  plots$p2 <- ggplot(data = iris) + geom_point(mapping = aes(x = Sepal.Length, y = Sepal.Width))
  plots$p3 <- ggplot(data = iris) + geom_point(mapping = aes(x = Petal.Length, y = Sepal.Length))
  
  # Handle the download request.
  output$dl <- downloadHandler(
    filename = function() input$exportFile,
    content = function(f) {
      # Start a PDF graphic device using the specified file.
      pdf(f)
      # Write each plot to a separate page.
      lapply(plots, print)
      # Turn off the device.
      dev.off()
    }
  )
  
}

# Run the application 
shinyApp(ui = ui, server = server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.