Reputation: 411
How to export plot_ly image as png from shiny app? I want to export png or jpg on action button 'ExportPlot' (as specified below). I know about plot_ly solution https://plot.ly/r/static-image-export/ however it require to create user on plot_ly as i read about it.
I would be grateful for any tips/solution.
library(shiny)
library(plotly)
ui <- fluidPage(
actionButton('ExportPlot', 'Export as png'),
plotlyOutput("plot"),
verbatimTextOutput("event")
)
server <- function(input, output) {
# renderPlotly() also understands ggplot2 objects!
output$plot <- renderPlotly({
plot_ly(mtcars, x = ~mpg, y = ~wt)
})
output$event <- renderPrint({
d <- event_data("plotly_hover")
if (is.null(d)) "Hover on a point!" else d
})
}
shinyApp(ui, server)
Upvotes: 1
Views: 3672
Reputation: 466
Here is the solution which provides download on click:
library(shiny)
library(plotly)
ui <- fluidPage(
downloadButton('ExportPlot', 'Export as png'),
plotlyOutput("plot")
)
server <- function(input, output) {
# generate the plot
thePlot <- reactive({
p <- plot_ly(mtcars, x = ~mpg, y = ~wt)
})
# renderPlotly()
output$plot <- renderPlotly({
thePlot()
})
# download
output$ExportPlot <- downloadHandler(
# file name
filename <- 'plot.png',
# content
content = function(file){
# create plot
export(p = thePlot(), file = 'tempPlot.png')
# hand over the file
file.copy('tempPlot.png',file)
}
)
}
shinyApp(ui, server)
Please note: With the RStudio browser/viewer the file name which is set per default is not correctly hand over, with external Browsers (e.g. Firefox) it should work.
Upvotes: 2