如何在downloadHandler中调用由响应式函数生成的图表

3

如何在不重新定义的情况下调用使用反应式函数创建的图表,以供downloadHandler使用?

以下是一个无法工作的示例:

# Part of server.R

output$tgPlot <- renderPlot({
 plot1 <-ggplot(iris[iris$Species==input$species,])+geom_point(aes(Sepal.Length ,Sepal.Width))
 print(plot1)

 } ) 



  output$plotsave <- downloadHandler(
    filename = 'plot.pdf',
    content = function(file){
      pdf(file = file, width=12, height=4)
      tgPlot()
      dev.off()
    }
  )

为什么无法在downloadHandler中调用tgPlot()?是否有其他方法?
1个回答

5

tgPlot()是在其他地方定义的函数吗?我没有看到你定义它。

你可能希望在一个普通(非响应式)函数中定义绘图代码,并从两个函数中引用它,例如:

tgPlot <- function(inputSpecies){
 plot1 <-ggplot(iris[iris$Species==inputSpecies,])+geom_point(aes(Sepal.Length ,Sepal.Width))
 print(plot1)
}

output$tgPlot <- renderPlot({
    tgPlot(input$species)
}) 

output$plotsave <- downloadHandler(
  filename = 'plot.pdf',
  content = function(file){
    pdf(file = file, width=12, height=4)
    tgPlot(input$species)
    dev.off()
  }
)

这将为您提供一个能够生成图表的函数。然后在响应式的renderPlot上下文中引用此函数,以生成响应式的图表或生成PDF文件。


谢谢,但那不是我的意思。我想调用output$tgPlot,类似于此处用于数据集的方法。https://dev59.com/H2Yr5IYBdhLWcg3wi6zd。当您有许多不同的条件图作为`output$tgPlot`的可能输出时,这将非常方便。 - Jonas Tundo
1
JT85,Jeff是正确的 - 你需要使用非响应式函数两次绘制图形。这是因为在一个情况下(renderPlot),正在呈现的是PNG,在另一个情况下,它是PDF,这些是两个完全不同的操作,只是恰好共享一些公共逻辑(即tqPlot)。 - Joe Cheng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接