Fab*_*ing 5 r knitr r-markdown shiny plotly
我想在 pdf 文件中添加一个情节图。这应该在本地完成(没有 plotly_IMAGE)。不幸的是,我无权访问 webshot(因为我无权安装 PhantomJS)。因此,我尝试了此处描述的解决方法:https : //github.com/ropensci/plotly/issues/311使用闪亮的小工具。但是我想对其进行调整,以便在不单击小工具中完成复制的情况下完成复制。
我所有的尝试(见下文)都失败了,因为我无法延迟 downloadHandler 直到复制完成。
任何建议如何在单击“下载”按钮后按顺序完成所需的结果(首先将 plotly-Image 复制为 png,然后在 pdf-Export 中使用它)?
用户界面:
library(shiny)
library(plotly)
library(rsvg)
shinyUI(fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'),
tags$script('
document.getElementById("downloadReport").onclick = function() {
var plotly_svg = Plotly.Snapshot.toSVG(
document.querySelectorAll(".plotly")[0]
);
Shiny.onInputChange("plotly_svg", plotly_svg);
};
')
),
mainPanel(
plotlyOutput('regPlot')
)
)
))
Run Code Online (Sandbox Code Playgroud)
服务器:
library(shiny)
library(plotly)
library(rsvg)
shinyServer(function(input, output, session) {
output$regPlot <- renderPlotly({
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
print("render")
p <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
mode = "markers", color = carat, size = carat)
p
})
observeEvent(input$plotly_svg, priority = 10, {
png_gadget <- tempfile(fileext = ".png")
png_gadget <- "out.png"
print(png_gadget)
rsvg_png(charToRaw(input$plotly_svg), png_gadget)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('testreport.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'testreport.Rmd')
library(rmarkdown)
out <- render('testreport.Rmd', params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1968 次 |
| 最近记录: |