简体   繁体   中英

Plotly embedded into Shiny and in RMarkdown

I would like to download Report within Shiny App, which includes Plotly graph. So far i have not found any answer on stackoverflow. Till this moment im able to download the screenshot of Plotly but it appears only in my working directory and it is not sent to Rmarkdown .

Example code:

library(shiny)
library(plotly)
library(rsvg)
library(ggplot2)

d <- data.frame(X1=rnorm(50,mean=50,sd=10),X2=rnorm(50,mean=5,sd=1.5),Y=rnorm(50,mean=200,sd=25))

ui <-fluidPage(
  title = 'Download report',
  sidebarLayout(

    sidebarPanel(
      helpText(),
      radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
                   inline = TRUE),
      downloadButton('downloadReport'),
      tags$script('
                  document.getElementById("downloadReport").onclick = function() {
                  var plotly_svg = Plotly.Snapshot.toSVG(
                  document.querySelectorAll(".plotly")[0]
                  );

                  Shiny.onInputChange("plotly_svg", plotly_svg);
                  };
                  ')
      ),
    mainPanel(
      plotlyOutput('regPlot')
    )
      )
)

server <- function(input, output, session) {

  output$regPlot <- renderPlotly({
    p <- plot_ly(d, x = d$X1, y = d$X2,mode = "markers")
    p
  })

  observeEvent(input$plotly_svg, priority = 10, {
    png_gadget <- tempfile(fileext = ".png")
    png_gadget <- "out.png"
    print(png_gadget)
    rsvg_png(charToRaw(input$plotly_svg), png_gadget)
  })

  output$downloadReport <- downloadHandler(
    filename = function() {
      paste('my-report', sep = '.', switch(
        input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
      ))
    },

    content = function(file) {
      src <- normalizePath('testreport.Rmd')

      owd <- setwd(tempdir())
      on.exit(setwd(owd))
      file.copy(src, 'testreport.Rmd')

      library(rmarkdown)
      out <- render('testreport.Rmd', params = list(region = "Test"), switch(
        input$format,
        PDF = pdf_document(), HTML = html_document(), Word = word_document()
      ))
      file.rename(out, file)
    }
  )
}

shinyApp(ui = ui, server = server)

and testreport.Rmd file:

---
title: "test"
output: pdf_document
params:
  name: "Test"
  region: 'NULL'
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Any help would be appreciated, because there is not many sources and documentations about R Plotly .

Cheers

If out.png is downloaded to your working directory, you can modify the content function of your downloadHandler to move it to the temporary directory and add it to the report:

content = function(file) {
      temp_dir <- tempdir()
      tempReport <- file.path(temp_dir, 'testreport.Rmd')
      tempImage <- file.path(temp_dir, 'out.png')
      file.copy('testreport.Rmd', tempReport, overwrite = TRUE)
      file.copy('out.png', tempImage, overwrite = TRUE)

      library(rmarkdown)
      out <- render(tempReport, params = list(region = "Test"), switch(
        input$format,
        PDF = pdf_document(), HTML = html_document(), Word = word_document()
      ))
      file.rename(out, file)
    }

Your testreport.Rmd could look like (more info here ):

---
title: "test"
---

Here's the plot image.

![Plot image](out.png)

You could also pass the arguments of your plotly function in the render of your content function as explained here and use a parametrized Rmarkdown file but this only works for Html reports.

Depending on how deep you want to dive into this, I would suggest creating a .brew file with your shiny code and than you can have your user send the information to the brew file and create the plot. This would give you a static code file which is updated dynamically with new data, each time. The only draw back is that when you make changes to shiny you have to make the same changes to your brew file. The other option is to create a flex dashboard with rmarkdown using the new RStudio 1.0 which becomes a html file. See ( Create parametric R markdown documentation? ) for brew example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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