本文介绍了在Shiny R中将多个图保存在单个PDF中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下载处理程序将Shiny App中的ggplots导出为单个PDF文件,但无法正常工作.PDF文件已保存,但仅给我最后一个ggplot,而不是全部三个.任何帮助将不胜感激!

I am trying to export ggplots in my Shiny App into a single PDF file using the download handler but it is not working. The PDF file is getting saved but it gives me only the last ggplot instead of all three. Any help would be appreciated!

下面是服务器的代码:

shinyServer(function(input, output, session) {
plotinput()
{
df<-data.frame(q=c(1,3,5,7,9),w=c(2,4,6,8,10),z=c(1,2,3,4,5))
ggplot(df,aes(x=q,y=w))+geom_point()
ggplot(df,aes(x=z,y=w))+geom_point()
ggplot(df,aes(x=q,y=z))+geom_point()
}
output$allgraphs <- downloadHandler(
filename = function(){paste0("graphs.pdf")},
content = function(file){
pdf(file,onefile = TRUE)
print(plotinput())
dev.off()
}
)
})

推荐答案

我们可以这样做

library(shiny)
library(grid)
library(gridExtra)



runApp(list(
  ui = fluidPage(downloadButton('allgraphs')),
  server = function(input, output) {

    plotinput <- function() {
      df<-data.frame(q=c(1,3,5,7,9),w=c(2,4,6,8,10),z=c(1,2,3,4,5))
      list(p1 = ggplot(df,aes(x=q,y=w))+geom_point(),
      p2 =  ggplot(df,aes(x=z,y=w))+geom_point(),
      p3 = ggplot(df,aes(x=q,y=z))+geom_point())
    }

    output$allgraphs = downloadHandler(
      filename = 'graphs.pdf',
      content = function(file) {
       pdf(file)

        arrangeGrob(print(plotinput()[['p1']]),
                    print(plotinput()[['p2']]),
                    print(plotinput()[['p3']]), ncol = 3)
        dev.off()
      })
  }
))

-输出

allgraphs.pdf

allgraphs.pdf

1

2

3

这篇关于在Shiny R中将多个图保存在单个PDF中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 21:36