0
votes

I have a Shiny App that generates multiple plots based on a selected filter, for each plot in the Server part I filter the data based on the selected Input filter:

output$plot_1 <- renderPlot({     
     df <- df %>% filter(df$filter == input$age)
     #plot code here
  })

output$plot_2 <- renderPlot({     
     df <- df %>% filter(df$filter == input$age)
     #plot code here
  })

I have to do this (filter the df inside the renderPLot function) for ALL plots. Is it possible to do it outside of renderPlot so that filtered df is available for all plots?

1
filtered_df <- shiny::reactive({df %>% filter(filter == input$age)}), then you can use filtered_df() in you renderPlot functionsPascal Schmidt

1 Answers

1
votes

Sure, we can store our filtered data in a reactive, so we can use it in multiple places. Note the double brackets when using a reactive, i.e. df_filtered()

Here is a minimal working example showing data being stored in a reactive and used in two plots.


library(shiny)
library(dplyr)

ui <- fluidPage(
  
    selectInput("mydropdown", "Select Species", choices = unique(iris$Species)),
    
    plotOutput("plot_1"),
    
    plotOutput("plot_2")
    
)

server <- function(input, output, session) {
    
    #Reactive
    df_filtered <- reactive({
        
        df <- filter(iris, Species == input$mydropdown)
        
        return(df)
        
    })
    
    #Plot 1
    output$plot_1 <- renderPlot({
        
        plot(df_filtered()$Petal.Length)
        
    })
    
    #Plot 2
    output$plot_2 <- renderPlot({
        
        plot(df_filtered()$Petal.Width)
        
    })
    
}

shinyApp(ui, server)