saving multiple plots in a single PDF in Shiny R

一曲冷凌霜 提交于 2021-02-08 07:41:03

问题


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!

Below is the code of the server:

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()
}
) 
})

回答1:


We could do this with

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()
      })
  }
))

-output

allgraphs.pdf

1

2

3



来源:https://stackoverflow.com/questions/49229329/saving-multiple-plots-in-a-single-pdf-in-shiny-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!