Download multiple plotly plots to PDF Shiny

前端 未结 2 1110
南旧
南旧 2021-02-15 12:35

My Shiny App displays a plotly plot for whatever input the user selects. I want a download button that saves ALL the plots inside a PDF file on the user\'s system. I\'m using R

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 12:41

    I think @Stanislaus Stadlmann is on point. For some reason, plotly::export does not work inside a loop of a rmarkdown file. I suspect it is for the same reason knitr::include_graphic does not work inside a loop. A workaround is to use the markdown syntax to insert your images. Here is the rmarkdown file that works:

    ---
    title: "Report"
    output: pdf_document
    always_allow_html: yes
    params:
      n: NA
    ---
    
    ```{r,echo=FALSE,warning=FALSE, results="asis"}
    library(plotly)
    
    for (item in params$n) {
      tmpFile <- tempfile(fileext = ".png")
      export(item, file = tmpFile)
      cat("![](",tmpFile,")\n")
    }
    ```
    

    And this is my downloadplot1 function:

      output$downloadplot1 <-  downloadHandler(
        filename = "plots.pdf",
        content = function(file){
    
          tempReport <- file.path(tempdir(), "report1.Rmd")
          file.copy("download_content.Rmd", tempReport, overwrite = TRUE)
    
          list.of.measurands <- c("Measurand1", "Measurand2") #....all my measurands
    
          plots.gen <- lapply(list.of.measurands, function(msrnd){
            plot_ly(dummy.df, x = c(1:nrow(dummy.df)), y = ~get(msrnd), type = 'scatter', mode = 'markers')
          })
    
          params <- list(n = plots.gen)
    
          rmarkdown::render(tempReport, output_file = file,
                            params = params,
                            envir = new.env(parent = globalenv())
          )
        }
      )
    

提交回复
热议问题