ss10
ss10

Reputation: 101

How to use DownloadButton to download dynamic number of plots

I hope you are well.
I need your help please.
My own shiny-server app is similar to this app and I would like to add to mine a downloadButton at the top :

max_plots <- 5

ui <- fluidPage(

  headerPanel("Dynamic number of plots"),

  sidebarPanel(
    sliderInput("n", "Number of plots", value=1, min=1, max=5)
  ),

  mainPanel(
    uiOutput("plots")
  )
)

server <- function(input, output) {

  output$plots <- renderUI({
    plot_output_list <- lapply(1:input$n, function(i) {
      plotname <- paste("plot", i, sep="")
      plotOutput(plotname, height = 280, width = 250)
    })

    do.call(tagList, plot_output_list)
  })

  for (i in 1:max_plots) {
    local({
      my_i <- i
      plotname <- paste("plot", my_i, sep="")

      output[[plotname]] <- renderPlot({
        plot(1:my_i, 1:my_i,
             xlim = c(1, max_plots),
             ylim = c(1, max_plots),
             main = paste("1:", my_i, ".  n is ", input$n, sep = "")
        )
      })
    })
  }
}

shinyApp(ui, server)

Is it possible to add a downloadbutton to download the 5 graphs in pdf?

Thanks :)

Upvotes: 1

Views: 102

Answers (1)

lz100
lz100

Reputation: 7330

Here you go :)

max_plots <- 5

ui <- fluidPage(
  
  headerPanel("Dynamic number of plots"),
  
  sidebarPanel(
    sliderInput("n", "Number of plots", value=1, min=1, max=5),
    downloadButton("pdf")
  ),
  
  mainPanel(
    uiOutput("plots")
  )
)

server <- function(input, output) {
  
  output$plots <- renderUI({
    lapply(1:input$n, function(i) {
      plotOutput(paste0("plot", i), height = 280, width = 250)
    })
  })
  
  plot_lists <- reactiveValues()
  
  for(i in 1:max_plots) {
    local({
      my_i <- i
      plotname <- paste0("plot", my_i)
      output[[plotname]] <- renderPlot({
        plot(
          1:my_i, 1:my_i,
          xlim = c(1, max_plots),
          ylim = c(1, max_plots),
          main = paste("1:", my_i, ".  n is ", input$n, sep = "")
        )
        plot_lists[[as.character(my_i)]] <- recordPlot()
      })
    })
  }
  output$pdf <- downloadHandler(
    filename = "my_plots.pdf",
    content = function(file) {
      pdf(file)
      sapply(rev(reactiveValuesToList(plot_lists)), print)
      dev.off()
    }
  )
}

shinyApp(ui, server)


Upvotes: 1

Related Questions