3

How to save plot using download button in shiny?
I know how to do it for ggplot, but I can't find how to do it for basic plot().

Example:

library(shiny)
library(ggplot2)


# ui
ui <- fluidPage(
  downloadButton("save", "save")
)


# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      ggsave(p(), filename = file)
    })
}


# run
shinyApp(ui, server)

above there is implemented saving the plot p. Now how to implement saving the plot p2 ?

Alfonso
  • 644
  • 7
  • 17
W W
  • 769
  • 1
  • 11
  • 26

1 Answers1

3

You can write it on a png object using device graphics. Check the code.

library(shiny)
library(ggplot2)


# ui
ui <- fluidPage(
  downloadButton("save", "save")
)


# server
server <- function(input, output){

  p <- reactive({ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()})
  p2 <- reactive({dotchart(iris$Sepal.Length, iris$Species, iris$Species)})

  output$save <- downloadHandler(
    file = "save.png" , # variable with filename
    content = function(file) {
      #ggsave(p(), filename = file)
      png(file = file)
      p2()
      dev.off()
    })
}


# run
shinyApp(ui, server)
Alfonso
  • 644
  • 7
  • 17
amrrs
  • 6,215
  • 2
  • 18
  • 27