rplotshinysaveggtern

Save ggtern plots in R Shiny


What to add in server in order to save the plot as either png or svg?

Does ggsave work with ggtern? (which is an extension to ggplot for ternary plots)

Here is a minimal reproducible example of what I'm trying to do in Shiny:

library(shiny)
library(ggtern)
library(tidyverse)



ui <- fluidPage(

    downloadButton("dwnld", label = "Save plot"),
    plotOutput("ternary")
)


server <- function(input, output) {
    # ternary plot via ggtern
    output$ternary <- renderPlot({
        data <- tibble(x = 0.2, y = 0.3, z = 0.5)
        plot <- ggtern(data, aes(x = x, y = y, z = z)) + geom_point(size = 8)
        print(plot)
        
    })
    
    # download the plot
    #????????
}

 
shinyApp(ui = ui, server = server)

Solution

  • You can proceed as follows:

    myPlot <- reactive({
      data <- tibble(x = 0.2, y = 0.3, z = 0.5)
      ggtern(data, aes(x = x, y = y, z = z)) + geom_point(size = 8)
    })
    
    output[["ternary"]] <- renderPlot({
      myPlot()
    })
    
    output[["dwnld"]] <- downloadHandler(
      filename = "myPlot.png",
      content = function(file){
        ggsave(file, myPlot())
      }
    )