You can wrap the resulting plotly object in reactive
or reactiveVal
to pass it to the output
and the downloadHandler
:
library(shiny)
library(plotly)
writeLines(con = "report.Rmd", text = "---
title: 'Plotly report'
output: html_document
params:
plotly_object: NA
---
```{r plotlyout, echo=FALSE, message=FALSE, out.width='100%'}
params$plotly_object
```")
ui = fluidPage(
plotlyOutput("Plot"),
downloadButton("report_button", "Generate report")
)
server = function(input, output, session) {
irisPlot <- reactive({
p <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(color=Species, shape=Species)) +
labs(title = "Iris sepal width vs length")
ggplotly(p)
})
output$Plot <- plotly::renderPlotly({
irisPlot()
})
output$report_button <- downloadHandler(
filename = "report.html",
content = function(file) {
tempReport <- tempfile(fileext = ".Rmd") # make sure to avoid conflicts with other shiny sessions if more params are used
file.copy("report.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render(tempReport, output_format = "html_document", output_file = file, output_options = list(self_contained = TRUE),
params = list(plotly_object = irisPlot())
)
}
)
}
shinyApp(ui, server)
Another approach is using htmlwidgets::saveWidget
(If you only need the html plot):
library(shiny)
library(plotly)
ui = fluidPage(
plotlyOutput("Plot"),
downloadButton("report_button", "Generate report")
)
server = function(input, output, session) {
irisPlot <- reactive({
p <- ggplot(data=iris, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_point(aes(color=Species, shape=Species)) +
labs(title = "Iris sepal width vs length")
ggplotly(p)
})
output$Plot <- plotly::renderPlotly({
irisPlot()
})
output$report_button <- downloadHandler(
filename = "report.html",
content = function(file) {
htmlwidgets::saveWidget(widget = partial_bundle(irisPlot()), file = file, selfcontained = TRUE)
}
)
}
shinyApp(ui, server)