nississippi
nississippi

Reputation: 327

How to download a autoplot graphic in Shiny?

I have a Shiny app, which creates a forecast graphic by using the autoplot function. As inputs, the user can upload a file and choose the number of months to be forecasted. So I work with reactive data.

The plot creation part looks like this:

forecast_graphic <- function() ({

if(is.null(data())){return()}

#create dataframe
df <- as.data.frame(data())
df <- select(df, column())
df <- as.data.frame(sapply(df, as.integer))

#create ts object and do data preprocessing for it
year <- as.integer(substr(startDatum(),1,4))
month <- as.integer(substr(startDatum(),6,7))
day <- as.integer(substr(startDatum(),9,10))

monthlyts <- ts(df, start =c(year,month,day), frequency = 12)

#create forecast model
ets <- ets(monthlyts)

#do forecasting
period <- as.integer(fcperiod())
forecastets <- forecast(ets, h= period)

#plot forecast
x <- autoplot(forecastets) +
  labs(x="Jahr", y = "") +
  ggtitle("") +
  scale_y_continuous(labels = format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  geom_forecast(h=period)

x

})

Now I want to give the possibility to download the graphic. I startet like this and the download also starts, but never comes to an end:

output$download3 <- renderUI({
  req(input$file)
  downloadButton('downloadData3', label = 'Download Diagramm')
})


 output$downloadData3 <- downloadHandler(
   #Specify filenames
   filename = function() {
  "forecast.png"
},

content = function(file){
 pdf(file)
 forecast_graphic()

}

Has anybody an idea?

Upvotes: 0

Views: 85

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84719

The solution is

output$downloadData3 <- downloadHandler(
  filename = function() {
    "forecast.png"
  },
  content = function(file){
    pdf(file)
    print(forecast_graphic())
    dev.off()
  }
)

Alternatively, since your graphic is a ggplot, I think you can do

output$downloadData3 <- downloadHandler(
  filename = function() {
    "forecast.png"
  },
  content = function(file){
    ggsave(file, forecast_graphic())
  }
)

Upvotes: 3

Kurt
Kurt

Reputation: 5

You could try to use plotly and the ggplotly() function to achieve this. In the standard output generated by it there will be a button included giving you the option to Download plot as a png (and other useful buttons like zooming in and out).

Look here for a guide on how to use it and examples: https://plot.ly/ggplot2/

Without testing it on your example I would try something like:

library(plotly)
ggplotly(x)

Upvotes: 0

Related Questions