1

I'm trying to figure out how to save reactive ggplots in my R Shiny project. I've followed this guide as well as the guide on the R Shiny website. However, I think I may be having an issue since I'm using reactive plots.

Here is the code I have so far.

ui <- fluidPage(

    dashboardBody(
      fluidRow(uiOutput('topbox')),
      fluidRow(
        tabBox(
          id = 'tabset1',
          width = '100%',
          tabPanel('Grades Graph', downloadButton('Download'), plotOutput('individualGraph')),
        )
      )
    )
  )

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

  grades <- reactive({
    req(input$file)
    inFile <- input$file
    if (endsWith(inFile$name, '.xlsx')){
      gradesTbl <- read_excel(inFile$datapath)
      gradesTbl <- gradesTbl %>% 
        arrange(Period, Student, Date, Type) %>% 
        mutate(Date = as.Date(Date))
      return(gradesTbl)
    } else if (endsWith(inFile$name, 'csv')){
      gradesTbl <- read_csv(inFile$datapath)
      gradesTbl <- gradesTbl %>% 
        arrange(Period, Student, Date, Type) %>% 
        mutate(Date = mdy(Date))
      return(gradesTbl)
    }
  })

  output$Download <- downloadHandler(
   filename = function(){
     paste('test', '.png', sep = '')
   },
   content = function(file){
     ggsave(file, plot = output$individualGraph, device = 'png')
   }
  )

  indivdf <- function(){
    data.frame(grades()) %>%
      filter((Student == input$studentVar) & (Period == input$periodVar) & (Type %in% input$typeVar) & (Unit %in% input$unitVar))
  }

  output$individualGraph <- renderPlot({
    req(input$periodVar)
    indivdf() %>%
      ggplot(aes(x = Date, y = Grade,
                 color = Type, shape = Unit)) +
      geom_point(size = 4) +
      ggtitle(paste(input$studentVar, "'s Individual Grades", sep = '')) +
      plotTheme() +
      scale_shape_manual(values = 1:10) +
      facet_wrap(Unit~.) +
      scale_color_manual(values = c('#E51A1D', '#377DB9', '#4EAE4A'))
  })

shinyApp(ui = ui, server = server)

The full code is here, but I think this is everything to show what I'm trying to do. I just can't figure out how to save these tables and plots that are reactive. I feel like it's something to do with using 'plot = output$indididualGraph', but I truly don't know.

Thomas Kellough
  • 143
  • 1
  • 2
  • 11

1 Answers1

8

You need to take the code to generate the plot and move it from the renderPlot into a reactive. Then you can call the same reactive from inside a renderPlot to display the graph in the UI and from your downloadHandler to download the plot.

See the example below. Using the same variable name for the reactive (individualGraph()) and the output return (output$individualGraph) may not be the best coding practise but I find it more convenient.

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

    individualGraph <- reactive({
        req(input$periodVar)
        indivdf() %>%
            ggplot(aes(x = Date, y = Grade,
                       color = Type, shape = Unit)) +
            geom_point(size = 4) +
            ggtitle(paste(input$studentVar, "'s Individual Grades", sep = '')) +
            plotTheme() +
            scale_shape_manual(values = 1:10) +
            facet_wrap(Unit~.) +
            scale_color_manual(values = c('#E51A1D', '#377DB9', '#4EAE4A'))
    })

    output$individualGraph <- renderPlot({
        req(individualGraph())
        individualGraph()
    })

    output$Download <- downloadHandler(
        filename = function(){
            paste('test', '.png', sep = '')
        },
        content = function(file){
            req(individualGraph())
            ggsave(file, plot = individualGraph(), device = 'png')
        }
    )

    grades <- reactive({
        req(input$file)
        inFile <- input$file
        if (endsWith(inFile$name, '.xlsx')){
            gradesTbl <- read_excel(inFile$datapath)
            gradesTbl <- gradesTbl %>% 
                arrange(Period, Student, Date, Type) %>% 
                mutate(Date = as.Date(Date))
            return(gradesTbl)
        } else if (endsWith(inFile$name, 'csv')){
            gradesTbl <- read_csv(inFile$datapath)
            gradesTbl <- gradesTbl %>% 
                arrange(Period, Student, Date, Type) %>% 
                mutate(Date = mdy(Date))
            return(gradesTbl)
        }
    })

    indivdf <- function(){
        data.frame(grades()) %>%
            filter((Student == input$studentVar) & (Period == input$periodVar) & (Type %in% input$typeVar) & (Unit %in% input$unitVar))
    }
}  
divibisan
  • 11,659
  • 11
  • 40
  • 58
Remy G
  • 96
  • 4
  • Thank you so much! That fixed it. Sorry it took me so long to reply. I ran into some issues getting the filename to work. After a lot of trial and error, I found it only works when I run it in my browser, but not running it in R Studio itself. Thanks again for the solution! – Thomas Kellough Aug 26 '18 at 21:44