2015-04-17 34 views
0

我試圖在Shiny中下載非ggplot文件。我可以看到應用程序中的情節,但是當我單擊UI中的plotDownload按鈕時,它會下載一個EMPTY png文件。有人可以知道我做錯了什麼?在Shiny中保存PNG圖非ggplot

server.R

library(shiny) 
shinyServer(
    function(input, output) { 

     plotInput <- reactive({ 
     plot(rnorm(sample(100:1000,1))) 
     }) 

     output$pngPlot <- renderPlot({ plotInput() }) 


     output$downloadPlot <- downloadHandler(
     filename = "myPlot.png", 
     content = function(file){ 
      png(file, width=800, res=100) 
      print(plotInput()) 
      dev.off() 
     })  
    } 
) 

ui.R

require(shiny) 
pageWithSidebar(
    headerPanel("Output to png"), 
    sidebarPanel(
    downloadButton('downloadPlot') 
), 
    mainPanel({ mainPanel(plotOutput("pngPlot")) }) 
) 

Thnks。

回答

1

您需要的downloadHandler()內重新繪製:

library(shiny) 
shinyServer(
    function(input, output) { 

    plotInput <- reactive({ 
     plot(rnorm(sample(100:1000,1))) 
    }) 

    output$pngPlot <- renderPlot({ plotInput() }) 


    output$downloadPlot <- downloadHandler(
     filename = "myPlot.png", 
     content = function(file){ 
     png(file, width=800, res=100) 
     plot(rnorm(sample(100:1000,1))) 
     dev.off() 

     })  
    } 
)