Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloadhander (save plot) for basic plot in shiny

Tags:

r

shiny

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 ?

like image 684
W W Avatar asked Jul 31 '26 09:07

W W


1 Answers

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)
like image 175
amrrs Avatar answered Aug 03 '26 00:08

amrrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!