downloadButton在闪亮的服务器中下载多个renderPlot反应式

时间:2019-05-22 15:54:30

标签: r ggplot2 shiny plotly

我正在创建一个显示几个图形的闪亮应用程序。我想通过按钮下载,下载所有图形显示

我执行以下操作:

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 个答案:

答案 0 :(得分:0)

这是一种方法。

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)