简体   繁体   English

如何在 R shiny 中将多个图下载为 zip 文件?

[英]how to download multiple plots as a zip file in R shiny?

I am implementing an R shiny with a function of downloading multiple plots in the png format.我正在实现一个 R shiny 和一个 function 下载多个 png 格式的图。 Currently, I am using the pdf format, which is able to contain multiple plots in one file.目前,我使用的是 pdf 格式,它能够在一个文件中包含多个绘图。 However, I prefer to save each individual plot as *.png and download them together as a zip file in a pre-specified directory.但是,我更喜欢将每个单独的 plot 保存为 *.png 并将它们作为 zip 文件一起下载到预先指定的目录中。 I checked many on-line resources, but can not figure it out.我查了很多网上资源,但都搞不清楚。 Below is the R code for downloading plots in the pdf format.下面是 R 代码,用于下载 pdf 格式的图。 Thank you for your help.谢谢您的帮助。

# download plot
 output$downloadPlot <- downloadHandler(

   # specify the file name
   filename=function(){
     paste0("individualPlots_", input$username, "_", Sys.Date(), ".pdf")
   },
   content=function(file){

     pdf(file, width=8, height=8)

     xrange <- c(as.numeric(input$threshold.start), as.numeric(input$threshold.end))
     for(i in 1:nrow(summary_output())){

       yrange <- c(0, ymax()[i]) 
       plot(yfit()[[i]] ~ datsub.x()[[i]], 
            col = "red", pch = 2,  
            xlim = xrange, ylim = yrange,
            xlab = "time (s)", ylab = "response (nm)", cex.lab = 1.5,
            main = substr(file.name()[i], 1, nchar(as.character(file.name()[i])) - 8), cex.main = 1.5)

       points(datsub.y()[[i]] ~ datsub.x()[[i]], pch = 20)

       legend("bottomright", c("fitted", "true"), col = c("red", "black"), 
              xpd = TRUE, horiz = TRUE, inset = c(-0.05, -0.15), pch = c(2, 20), bty = 'n', cex = 1.5)

       legend("top", c(paste0("kd = ", b.est()[i], " (1/s)"),
                       paste0("RMSE = ", y_rmse()[i])), 
              xpd = TRUE, horiz = TRUE, inset = c(-0.05, -0.065), bty = 'n', cex = 1.5)
     }
     dev.off()
   })

Below is an reproducible example:下面是一个可重现的例子:

ui.R ui.R


shinyUI( fluidPage(
  
  titlePanel( "Application Template"), br(),
  
  sidebarLayout(
    
    sidebarPanel(
      sliderInput( "sample.size", "Number of Samples:", min = 50, max = 500, value = 50),
      downloadButton( 'plot.download', 'Download Plots')
    ),
    
    # Display a histogram of the generated distribution
    mainPanel(
      fluidRow(
        column(6, plotOutput( "norm.plot")),
        column(6, plotOutput( "unif.plot"))
      )
    )
  )
  
))

server.R server.R

shinyServer(function(input, output){
   
  # Define a function that creates a histogram of random normal data
  norm.plot <- function(){
    
    # Generate data based on the slider input from the UI file
    samp <- rnorm(input$sample.size)
    
    # Plot a histogram of the random normal sample
    ggplot( data.frame( samp = samp), aes( x = samp)) +
      geom_histogram( bins = 30) +
      labs( x = 'Random Normal Draws', y = 'Count')
  }
  
  # Return the normal histogram to the app
  output$norm.plot <- renderPlot({
    return( norm.plot())
  })
  
  # Define a function that creates a histogram of random uniform data
  unif.plot <- function(){
    
    # Generate data based on the slider input from the UI file
    samp <- runif(input$sample.size)
    
    # Plot a histogram of the random uniform sample
    ggplot( data.frame(samp = samp), aes(x = samp)) +
      geom_histogram( bins = 30) +
      labs( x = 'Random Uniform Draws', y = 'Count')
  }
  
  # Return the uniform histogram to the app
  output$unif.plot <- renderPlot({
    return( unif.plot())
  })
  
  # Download the plots
  output$plot.download = downloadHandler(
    filename = 'plots.zip',
    content = function( file){
      
      # Set temporary working directory
      owd <- setwd( tempdir())
      on.exit( setwd( owd))
      
      # Save the histograms (a loop can be used here for a bunch of plots)
      ggsave( 'norm_hist.png', plot = norm.plot(), device = "png")
      ggsave( 'unif_hist.png', plot = unif.plot(), device = "png")
      
      # Zip them up
      zip( file, c( 'norm_hist.png', 'unif_hist.png'))
    }
  )
  
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM