r语言 - 如何在 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()
}

有人有想法吗?

解决方案是

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

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

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

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

library(plotly)
ggplotly(x)

最新更新