r - 将 Shiny(非 ggplot)图输出为 PDF

标签 r shiny knitr

是否有一种方法可以将(UI 端)Shiny 绘图输出为 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') .对于一个不错的基本模型,请尝试:

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")) })
)

关于r - 将 Shiny(非 ggplot)图输出为 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27276994/

相关文章:

将包和函数作为另一个函数中的参数引用

r - 如何制作重叠的条形图?

r - Shiny 没有像我期望的那样显示我的 ggplot

r - 在 Shiny 的R中使用plotly绘制多线图

r - 将 MATLAB 脚本集成到 R Markdown 文档中

r - 如何使用 rmarkdown::render() 在 html 中呈现 gganimate 图,而不产生不需要的输出

java - R 中的 MemoryError while read.xlsx

r - 获取Shiny中窗口的大小

r - 当数据更改时,ggvis 中的 linked_brush 无法在 Shiny 中工作

r - 为什么在包含 Rmarkdown 文件时,Shiny 应用程序布局会发生变化?