Shiny: use downloadHandler for a list of ggplot objects


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?


Try something like the following.


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

# 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.
      # Write each plot to a separate page.
      lapply(plots, print)
      # Turn off the device.

# 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.