1

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()
}
) 
})
Sidhant
  • 13
  • 4

1 Answers1

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

enter image description here

2

enter image description here

3

enter image description here

akrun
  • 874,273
  • 37
  • 540
  • 662