1

Trouble combining multiple shiny plots and downloading through a single click.

Code below is from the answer here: Solution I tried this solution. It works fine for two plots but as soon as I add another plot it only returns the graph information but not the graph themselves.

Combining two plots works fine.

I also tried other solutions but both of the solutions when implemented returns a text file instead of pdf or pdf file that is corrupted.
Solution1 Solution2

Any suggestion would be really appreciated. Thank you!

Code

  library(ggplot2)
  ui <- shinyUI(fluidPage(
  titlePanel("Test app"),
  fluidRow(
    column(4,
           wellPanel(
             downloadButton('download',label="Download plot as png")
           )
    ),
    column(8,
           plotOutput("plot")
    )  
  )
))
server <- function(input,output) {

  plotting<- reactive({

    data1=data.frame(x=rnorm(50),y=rnorm(50))
    data2=data.frame(x=rexp(50),y=rexp(50))
    data3=data.frame(x=rexp(50),y=rexp(50))


    plot1=ggplot(data1,aes(x,y))+geom_point()
    plot2=ggplot(data2,aes(x,y))+geom_point()
    plot3=ggplot(data3,aes(x,y))+geom_point()

    gb1=ggplot_build(plot1)
    gb2=ggplot_build(plot2)
    gb3=ggplot_build(plot3)

    gA <- ggplot_gtable(gb1)
    gB <- ggplot_gtable(gb2)
    gC <- ggplot_gtable(gb3)

    both <- gtable:::rbind_gtable(gA, gB, "last")
    all <- gtable:::rbind_gtable(both, gC, "last")
    return(all)
  })

  output$plot <- renderPlot({
    grid.newpage()
    grid.draw(plotting())
  })

  output$download <- downloadHandler(
    filename <- "shinytestplot.png",

  # Changes:
  content <- function(file){ ## file = NULL --> file
    png(file) # filename --> file
    grid.newpage()
    grid.draw(plotting())
    dev.off()
  }
  ) 
}
shinyApp(server=server,ui=ui)
tropicalbath
  • 121
  • 1
  • 1
  • 12

1 Answers1

2

Your example works just fine for me. However, I'd recommend against rbinding plots. Use the patchwork package instead.

library(ggplot2)
library(shiny)
library(patchwork)

ui <- shinyUI(fluidPage(
  titlePanel("Test app"),
  fluidRow(
    column(4,
           wellPanel(
             downloadButton('download',label="Download plot as png")
           )
    ),
    column(8,
           plotOutput("plot")
    )  
  )
))
server <- function(input,output) {

  plotting<- reactive({

    data1=data.frame(x=rnorm(50),y=rnorm(50))
    data2=data.frame(x=rexp(50),y=rexp(50))
    data3=data.frame(x=rexp(50),y=rexp(50))


    plot1=ggplot(data1,aes(x,y))+geom_point()
    plot2=ggplot(data2,aes(x,y))+geom_point()
    plot3=ggplot(data3,aes(x,y))+geom_point()

    # stack the plots on top of one another with patchwork
    plot1 / plot2 / plot3
  })

  output$plot <- renderPlot({
    print(plotting())
  })

  output$download <- downloadHandler(
    filename <- "shinytestplot.png",

    # Changes:
    content <- function(file){ 
      ggsave(file, plotting())
    }
  ) 
}
shinyApp(server=server,ui=ui)
Claus Wilke
  • 16,992
  • 7
  • 53
  • 104