I have the shiny app below from which Im trying to download the plotly graph through downloadHandler()
. The issue is that the object that Im trying to download is either a datatable or a plotly plot so I do not know how to pass it to the downloadHandler()
. Note that my download button is dynamic as well because in the first case it should download a table and in the second a plot. Note that I care just for the plot here.Open the app in browser.Firstly I install:
library(webshot)
install_phantomjs()
and then:
library(shiny)
library(plotly)
d <- data.frame(X1 = rnorm(50,mean=50,sd=10),
X2 = rnorm(50,mean=5,sd=1.5),
Y = rnorm(50,mean=200,sd=25))
ui <-fluidPage(
title = 'Download Plotly',
sidebarLayout(
sidebarPanel(
selectInput("S","SELECT",choices = c("Table","Plot"),selected = "Plot"),
uiOutput('down')
),
mainPanel(
uiOutput('regPlot')
)
)
)
server <- function(input, output, session) {
output$down<-renderUI({
if(input$S=="Table"){
output$downloadData <- downloadHandler(
filename = function() {
paste(input$filename, input$extension, sep = ".")
},
# This function writes data to a file given to it by the argument 'file'.
content = function(file) {
sep <- "txt"=","
# Write to a file specified by the 'file' argument
write.table(data.frame(mtcars), file, sep = sep,
row.names = FALSE)
}
)
downloadButton("downloadData", "Download",class = "butt1")
}
else{
output$downloadData <- downloadHandler(
filename = function(){
paste0(paste0("test", Sys.Date()), ".png")
},
content = function(file) {
export(regPlot, file=file)
})
downloadButton("downloadData", "Download",class = "butt1")
}
})
output$regPlot<-renderUI({
if(input$S=="Plot"){
output$pl<-renderPlotly(
plot_ly(d, x = d$X1, y = d$X2, mode = "markers"))
plotlyOutput("pl")
}
else{
output$tbl = DT::renderDataTable(datatable(
d
))
dataTableOutput("tbl")
}
})
}
shinyApp(ui = ui, server = server)
According to the ploty site use the following code: