闪亮:将动态情节输出到图像?

时间:2015-06-17 08:47:31

标签: r shiny dygraphs

我正在使用闪亮,我想创建一个下载按钮,将当前的情节存储为图像。这有效:

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

但是我使用dygraphs来绘制动态图,这会产生一个空的白色图像:

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

但是dygraphs的绘图代码一般都有效...因为在网页闪亮的应用程序中它正确地显示了情节。

1 个答案:

答案 0 :(得分:0)

这个问题相当陈旧,但也许这个答案可能对你或其他人有用。此问题与此问题直接相关:How to save Leaflet in R map as png or jpg file?。我遇到了同样的问题,这就是我如何解决它的问题:

您需要安装软件包“htmlwidgets”和“webshot”。然后,

library(htmlwidgets)
library(webshot)

您还需要安装PhantomJS。然后,

使用通用函数调用将绘图保存为服务器端的单独对象。您需要在单独的响应环境中创建变量ReshapedVariables,因此现在它将被视为一个函数:

dyplot <- function(){
dygraph(ReshapedVariables(), main=Title) %>%
labelsDiv="VariablePlotLegend", show="always")  %>%
dyLegend(labelsSeparateLines = FALSE,  labelsDiv="VariablePlotLegend",show="always") %>%
dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)}

然后下载:

output$downloadData <- downloadHandler(
filename = function () {paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content = function(file) {
  saveWidget(dyplot(), "temp.html", selfcontained = FALSE)
  webshot("temp.html", file = file)
}
 )