将Shiny(非ggplot)绘图输出为PDF

时间:2014-12-03 16:39:46

标签: r shiny knitr

是否有方法输出(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")
      })
  }
))

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:6)

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

<强> server.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)
            }
        )
    }
)

<强> ui.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")) })
)

答案 1 :(得分:3)

(您好),只需使用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)
      })
  }
)
相关问题