如何在Shiny中下载自动绘图图形?

时间:2019-01-31 08:46:25

标签: r graphics download shiny

我有一个Shiny应用程序,该应用程序使用自动绘图功能创建了一个预测图形。 作为输入,用户可以上传文件并选择要预测的月数。因此,我使用反应性数据。

情节创建部分如下所示:

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

})

现在,我希望可以下载图形。 我像这样开始,下载也开始了,但从未结束:

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()

}

有人有想法吗?

2 个答案:

答案 0 :(得分:2)

解决方案是

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

或者,由于您的图形是ggplot,我想您可以做到

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

答案 1 :(得分:0)

您可以尝试使用plotly和ggplotly()函数来实现此目的。在它生成的标准输出中,将包含一个按钮,使您可以选择将图档下载为png (以及其他有用的按钮,如放大和缩小)。

在此处查找有关如何使用它的指南和示例:https://plot.ly/ggplot2/

如果不对您的示例进行测试,我会尝试以下操作:

library(plotly)
ggplotly(x)