I am using shiny and I would like to create a download button which stores the current plot as image. this works:
output$downloadPlot <- downloadHandler(
filename <- function() {
paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content <- function(file) {
png(file, width = 980, height = 400, units = "px", pointsize = 12,
bg = "white", res = NA)
plot(sin, -pi, 2*pi)
dev.off()},
contentType = 'image/png'
)
But I am using dygraphs for dyanmic plots and this creates an empty white image:
output$downloadPlot <- downloadHandler(
filename <- function() {
paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content <- function(file) {
png(file, width = 980, height = 400, units = "px", pointsize = 12,
bg = "white", res = NA)
ReshapedVariables<-variablesForPlot()
if(input$timeframe == 1){
Title ="Timeframe: 1 Month"
} else if(input$timeframe==2){
Title ="Timeframe: 3 Months"
} else if(input$timeframe==3){
Title ="Timeframe: 6 Months"
} else if(input$timeframe==4){
Title ="Timeframe: Year to date"
} else if(input$timeframe==5){
Title ="Timeframe: 3 Years"
} else if(input$timeframe==6){
Title ="Timeframe: All"
} else {
Title ="Timeframe: Year to date"
}
dygraph(ReshapedVariables, main=Title) %>%
#dyLegend(width = 200, labelsSeparateLines = TRUE, labelsDiv="VariablePlotLegend", show="always") %>%
dyLegend(labelsSeparateLines = FALSE, labelsDiv="VariablePlotLegend", show="always") %>%
dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)
dev.off()},
contentType = 'image/png'
)
But the plot code for dygraphs works in general...because in the web shiny app it shows the plot correctly.
This question is rather old, but perhaps this answer may still be useful to you or somebody else. This question is directly related to this question: How to save Leaflet in R map as png or jpg file?. I was having the same problem you are and here is how I solved it for my case:
You'll need to install the packages "htmlwidgets" and "webshot". Then,
You will also need to install PhantomJS. Then,
Save your plot as a separate object on the server side with a generic function call. You'll need to create your variable ReshapedVariables within a separate reactive environment, so it will now be treated as a function:
and then the download: