是否有一种方法可以将(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/