R Shiny saving reactive ggplots

拜拜、爱过 提交于 2019-12-06 16:07:58
Remy G

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