从闪亮的应用程序将反应图保存为 png 到临时目录

Save reactive plot to temp directory as png from shiny app

这个问题很基础,和How to save reactive plot as png to working directory in a shiny app

之前的一些问题相关

我不得不改变我的策略,从 Rmarkdown 中的一个闪亮的应用程序创建一个情节。

为此我需要完成这个简单的任务:

如何将此绘图以 png 格式保存到临时文件夹?

背景:保存到临时文件夹后,我会将其传输到 R markdown 以创建报告。

library(shiny)

ui <- basicPage(
  plotOutput("plot1"),
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })
}
shinyApp(ui, server)

更新:我原来的代码是这样的。我无法提供一个可重现的例子,因为它太复杂了:

如何实现 ismirsehregal 对这段代码的回答:

# plot: Radarplot ------

output$radar <- renderChartJSRadar({
  chartJSRadar(PSA_13()[,c(1,2,6)],
               main = "XXX",
               maxScale = 100, scaleStepWidth = 10, scaleStartValue = 0, labelSize = 12, 
               addDots = TRUE, showToolTipLabel = TRUE, showLegend = TRUE, lineAlpha = 0.8, 
               polyAlpha = 0.2, responsive = FALSE, 
               colMatrix = col2rgb(c("orange", "navy" ,"grey")))
})

# create markdown report with radar plot ----------------------------------

output$report <- downloadHandler(
  filename = "report.pdf",
    content = function(file) {
      td <- tempdir()
      tempReport <- file.path(td, "report.Rmd")
      tempLogo <- file.path(td, "logo.png")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      file.copy("logo.png", tempLogo, overwrite = TRUE)
    
    params <- list(scores = PSA_13()[,c(1,2,6)])
                   
    
    rmarkdown::render(tempReport, output_file = file,
                      params = params,
                      envir = new.env(parent = globalenv())
    )
  }
)

report.Rmd

    ---
geometry: margin=20truemm
fontfamily: mathpazo
fontsize: 11pt
documentclass: article
classoption: a4paper
urlcolor: blue
output: 
    pdf_document
header-includes:
   - \usepackage{fancyhdr}
   - \pagestyle{fancy}
   - \rhead{\includegraphics[width = .05\textwidth]{logo.png}}
params: 
    scores: NA
    plot_object: NA
---
\pagenumbering{gobble}

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

```{r rectangle, echo=FALSE}
drawBox(x =1.3, y = 3.7, width = 2.5, height = 1)
```

\vspace{-80truemm}

```{r plotout, echo=FALSE, message=FALSE, out.width='100%'}
params$plot_object
```


<!-- ```{r, echo=FALSE, out.width="100%", } -->
<!-- chartJSRadar(params$scores, width = 700, height = 700, -->
<!--              main = "Peritoneal Surface Calculator Radarchart", -->
<!--              maxScale = 100, -->
<!--              scaleStepWidth = 10, -->
<!--              scaleStartValue = 0, -->
<!--              labelSize = 14, -->
<!--              addDots = TRUE, -->
<!--              showToolTipLabel = FALSE, -->
<!--              showLegend = TRUE, -->
<!--              lineAlpha = 0.8, -->
<!--              polyAlpha = 0.2, -->
<!--              responsive = FALSE, -->
<!--              colMatrix = col2rgb(c("orange", "navy" ,"grey"))) -->
<!-- ``` -->

我感觉离解决方案很近了,非常感谢您抽出时间!

有多个选项here。 在你的情况下,你可以选择这样一个简单的选项:

library(shiny)

ui <- basicPage(
  plotOutput("plot1"),
  actionButton("save", "Click to save")
)

server <- function(input, output) {
  output$plot1 <- renderPlot({
    plot(mtcars$wt, mtcars$mpg)
  })
  
  
  observeEvent("save", {
    png('C:/path/to/your_plot/plot_saved.png')
    plot(mtcars$wt, mtcars$mpg)
    dev.off()
  })
  
  
}
shinyApp(ui, server)

如果您想指定尺寸、分辨率等,您必须在 observeEvent

中自定义代码

不需要保存临时png文件。我们可以使用 recordPlot 代替:

library(shiny)
library(datasets)

writeLines(con = "report.Rmd", text = "---
title: 'Plot report'
output: html_document
params:
  plot_object: NA
---

```{r plotout, echo=FALSE, message=FALSE, out.width='100%'}
params$plot_object
```")

ui = fluidPage(
  plotOutput("plot1"),
  downloadButton("report_button", "Generate report")
)

server = function(input, output, session) {
  reactivePlot1 <- reactive({
    plot(mtcars$wt, mtcars$mpg)
    recordPlot()
  })
  
  output$plot1 <- renderPlot({
    reactivePlot1()
  })
  
  output$report_button <- downloadHandler(
    filename = "report.html",
    content = function(file) {
      tempReport <- tempfile(fileext = ".Rmd") # make sure to avoid conflicts with other shiny sessions if more params are used
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      rmarkdown::render(tempReport, output_format = "html_document", output_file = file, output_options = list(self_contained = TRUE),
                        params = list(plot_object = reactivePlot1())
      )
    }
  )
}

shinyApp(ui, server)

请看我的.


OP 更新后 - 使用虚拟数据:

app.R:

library(shiny)
library(radarchart)

scores <- data.frame("Label"=c("Communicator", "Data Wangler", "Programmer",
                               "Technologist",  "Modeller", "Visualizer"),
                     "Rich" = c(9, 7, 4, 5, 3, 7),
                     "Andy" = c(7, 6, 6, 2, 6, 9),
                     "Aimee" = c(6, 5, 8, 4, 7, 6))

ui = fluidPage(
  chartJSRadarOutput("radar", width = "450", height = "300"),
  downloadButton("report", "Generate report")
)

server = function(input, output, session) {
  reactiveRadar <- reactive({
    chartJSRadar(scores, maxScale = 10, showToolTipLabel=TRUE)
  })
  
  # plot: Radarplot ------
  output$radar <- renderChartJSRadar({
    reactiveRadar()
  })
  
  # create markdown report with radar plot ----------------------------------
  
  output$report <- downloadHandler(
    filename = "report.html",
    content = function(file) {
      td <- tempdir()
      tempReport <- file.path(td, "report.Rmd")
      # tempLogo <- file.path(td, "logo.png")
      file.copy("report.Rmd", tempReport, overwrite = TRUE)
      # file.copy("logo.png", tempLogo, overwrite = TRUE)
      
      params <- list(scores = "Test", plot_object = reactiveRadar()) # scores = PSA_13()[,c(1,2,6)]
      
      rmarkdown::render(tempReport, output_file = file,
                        params = params,
                        envir = new.env(parent = globalenv())
      )
    }
  )
}

shinyApp(ui, server)

report.Rmd:

---
geometry: margin=20truemm
fontfamily: mathpazo
fontsize: 11pt
documentclass: article
classoption: a4paper
urlcolor: blue
output: 
    html_document
header-includes:
   - \usepackage{fancyhdr}
   - \pagestyle{fancy}
   # - \rhead{\includegraphics[width = .05\textwidth]{logo.png}}
params: 
    scores: NA
    plot_object: NA
---
\pagenumbering{gobble}

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

```{r rectangle, echo=FALSE}
drawBox(x =1.3, y = 3.7, width = 2.5, height = 1)
```

\vspace{-80truemm}

```{r plotout, echo=FALSE, message=FALSE, out.width='100%'}
params$plot_object
```