如何使用观察者导出图?

时间:2015-01-08 21:12:09

标签: r pdf-generation shiny

我制作了一个小应用程序,试图学习使用闪亮的方法将图表导出到文件中。目前我正在尝试使用观察者,并且我已经成功地导出了情节,但不是我想要的方式。在大多数情况下,我使这个应用程序从闪亮的库中复制观察者演示,并更新以尝试做pdfs。用户界面只有两个操作按钮(输入$ ex,输入$ plot),以及一个用于更改样本大小的滑块。它输出两个相互正交的随机法线图。我尝试使用以下代码输出图表。

pdf.check<-reactive({
    #'this should change when you hit the plot button, or when you change the sample size,
    #'but not when you hit the export button. Whenever you hit the export button
    #'pdf.check!=input$ex
    input$n
    input$plot
    isolate({input$ex})
  })
  obs <- observer({
    if(input$ex>0 & input$ex!=isolate({pdf.check()})){
      #'when you hit the export button, this should start a pdf.  it shouldn't do it
      #'for any other input, or when you open the app
      pdf(file=logfilename, width=6, height = 5)
    }
    #'I included the input$plot to make this run whenever you hit the plot button, and
    #'it should just be making these graphs.
    input$plot
    #'isolated input$n so this code doesn't run when you change n
    isolate({plot(rnorm(input$n), rnorm(input$n), pch=20, xlab="X", ylab = "Y", main= input$plot)})

  })

这实际上做的是每次点击绘图按钮时导出为pdf,但在移动n滑块后它将不再导出。此外,如果我已经移动了n滑块,我必须按两次导出按钮才能启动pdf。我不太了解观察者知道我做错了什么。

我遇到的另一个问题是我无法让应用程序在关闭时运行dev.off()。我可以包含一些东西来手动运行dev.off(),但如果有人不小心关闭了应用程序,我希望pdf仍然关闭。我试图使用以下内容。

  session$onSessionEnded(function() {
    dev.off()
    unlink(logfilename)
  })

老实说,我对观察者来说仍然缺乏经验,而且我并不完全确定我理解它是如何运作的。我们将非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

您需要做的是将绘图函数包装在下载处理程序中而不是数据中。像这样的东西,其中observer()是创建绘图的函数:

output$downloadPlot <- downloadHandler(
    filename = function() {paste0(input$plot, ".pdf")},
    content = function(file) {
      pdf(file, width=8.5, height=5)
      observer()
      dev.off()      
    })

然后回到ui,您可以添加一个用于下载绘图的按钮(不同于仅在屏幕上显示绘图)。

downloadButton("downloadPlot", label="Download Plot")