R Shiny saving reactive ggplots

房东的猫 提交于 2019-12-08 08:23:22

问题


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.


回答1:


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))
    }
}  


来源:https://stackoverflow.com/questions/52029794/r-shiny-saving-reactive-ggplots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!