r语言 - 将闪亮(非 ggplot)绘图输出为 PDF



有没有办法将(UI端)闪亮的绘图输出到PDF供应用程序用户下载? 我已经尝试了各种类似于涉及 ggplot 的方法,但似乎downloadHandler无法以这种方式操作。 例如,以下内容仅生成无法打开的损坏的PDF。

library(shiny)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = reactive({
      plot(1:10)
    })
    output$foo = downloadHandler(
      filename = 'test.pdf',
      content = function(file) {
        plotInput()
        dev.copy2pdf(file = file, width=12, height=8, out.type="pdf")
      })
  }
))

非常感谢您的帮助。

已解决。 绘图应该用pdf()保存在本地,而不是屏幕设备(与dev.copy2pdf一样)。 这是一个工作示例:shiny::runGist('d8d4a14542c0b9d32786') . 对于一个不错的基本模型,请尝试:

服务器。R

library(shiny)
shinyServer(
    function(input, output) {
        plotInput <- reactive({
            if(input$returnpdf){
                pdf("plot.pdf", width=as.numeric(input$w), height=as.numeric(input$h))
                plot(rnorm(sample(100:1000,1)))
                dev.off()
            }
            plot(rnorm(sample(100:1000,1)))
        })
        output$myplot <- renderPlot({ plotInput() })
        output$pdflink <- downloadHandler(
            filename <- "myplot.pdf",
            content <- function(file) {
                file.copy("plot.pdf", file)
            }
        )
    }
)

用户界面。R

require(shiny)
pageWithSidebar(
    headerPanel("Output to PDF"),
    sidebarPanel(
        checkboxInput('returnpdf', 'output pdf?', FALSE),
        conditionalPanel(
            condition = "input.returnpdf == true",
            strong("PDF size (inches):"),
            sliderInput(inputId="w", label = "width:", min=3, max=20, value=8, width=100, ticks=F),
            sliderInput(inputId="h", label = "height:", min=3, max=20, value=6, width=100, ticks=F),
            br(),
            downloadLink('pdflink')
        )
    ),
    mainPanel({ mainPanel(plotOutput("myplot")) })
)

(您好),只需使用 pdf

library(shiny)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = reactive({
      plot(1:10)
    })
    output$foo = downloadHandler(
      filename = 'test.pdf',
      content = function(file) {
        pdf(file = file, width=12, height=8)
        plotInput()
        dev.off()
      })
  }
))

编辑:我不知道...这很奇怪。解决方法是像您最初所做的那样使用 dev.copy2pdf,但在 reactive 函数中而不是downloadHandler

## server.R
library(shiny)
shinyServer(
  function(input, output) {
    plotInput <- reactive({plot(rnorm(1000))
                           dev.copy2pdf(file = "plot.pdf")
                           })
    output$myplot <- renderPlot({ plotInput() })
    output$foo <- downloadHandler(
      filename <- "plot.pdf",
      content <- function(file) {
        file.copy("plot.pdf", file)
      })
  }
)

最新更新