Download button to download SVG images of my ggplot in Shiny? [min reprex]

I was able to adapt an answer from this thread into a suitable solution.

In this way, the plot only needs to be generated one time.

library(shiny)
library(ggplot2)
runApp(list(
  ui = fluidPage(downloadButton("downloadPlot"),
                 plotOutput("myplot")),
  
  
  server = function(input, output) {
    
    
    
      output$myplot <- renderPlot(.myplot())
      
      .myplot <- reactive(ggplot(mtcars, aes(x=mpg, y=cyl))+geom_point())
        

    plotInput = function() {
    
      ##################################################
      ##################################################
      .myplot()
      ##################################################
      ##################################################
      
    }
    output$downloadPlot <- downloadHandler(
      filename = function() { paste("test", '.svg', sep='') },
      content = function(file) {
        ggsave(file, plot = plotInput(), device = "svg")
      }
    )
  }
))
1 Like