首页 > 解决方案 > downloadButton 在闪亮的服务器中下载多个响应式渲染图

问题描述

我正在创建一个显示多个图形的闪亮应用程序。而且我会喜欢通过一个按钮下载,下载所有图形显示

我执行以下操作:

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")
  }
))

标签: rggplot2shinyplotly

解决方案


这是一种方法。

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)

推荐阅读