downloadButton to download multiple renderPlot reactive in shiny server

跟風遠走 提交于 2021-02-11 14:57:30

问题


I am creating a shiny application that displays several graphics. And I will like through a button download, download all graphs display

I do the following:

server = function(input, output) {
    df<-data.frame(q=c(1,3,5,7,9),w=c(2,4,6,8,10),z=c(1,2,3,4,5))

# output all plot
 output$p1 <- renderPlot({ 
   ggplot(df,aes(x=q,y=w)) + geom_point()
   })
 output$p2 <- renderPlot({ 
   ggplot(df,aes(x=z,y=w))+geom_point()
 })
 output$p3 <- renderPlot({ 
   ggplot(df,aes(x=q,y=z))+geom_point()
 })

# Here is my function to list all the reactive graphs in png
get_plot <- function(my_i){
path <- paste("p", my_i,".png", sep="")
   png(path)
   dev.off()
}

#The output button 
output$allgraphs = downloadHandler(
  filename =function() {
    'all_images.zip'
  }, 
 content = function(fname) {
 fs <- c()
 for (i in 1:3) {
      path <- paste("p", i, ".png", sep="")
      fs <- c(fs, path)
      get_plot(i)
    }
 zip::zipr(zipfile=fname, files=fs)
  },
  contentType = "application/zip")
  }
))

回答1:


Here is a way.

library(shiny)
library(ggplot2)

ui <- fluidPage(
  plotOutput("p1"), 
  plotOutput("p2"),
  plotOutput("p3"),
  downloadButton("allgraphs", "Download")
)

server = function(input, output) {
  df<-data.frame(q=c(1,3,5,7,9),w=c(2,4,6,8,10),z=c(1,2,3,4,5))

  p1 <- reactive({
    ggplot(df,aes(x=q,y=w)) + geom_point()
  })
  p2 <- reactive({
    ggplot(df,aes(x=z,y=w))+geom_point()
  })
  p3 <- reactive({
    ggplot(df,aes(x=q,y=z))+geom_point()
  })

  output$p1 <- renderPlot({ 
    p1()
  })
  output$p2 <- renderPlot({ 
    p2()
  })
  output$p3 <- renderPlot({ 
    p3()
  })

  output$allgraphs = downloadHandler(
    filename = function() {
      'all_images.zip'
    }, 
    content = function(fname) {
      fs <- replicate(3, tempfile(fileext = ".png"))
      ggsave(fs[1], p1())
      ggsave(fs[2], p2())
      ggsave(fs[3], p3())
      zip::zipr(zipfile=fname, files=fs)
    },
    contentType = "application/zip")
}

shinyApp(ui, server)


来源:https://stackoverflow.com/questions/56260758/downloadbutton-to-download-multiple-renderplot-reactive-in-shiny-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!