Search code examples
rggplot2shinyfacet-wrap

R shiny ggplot facet_wrap that depends on select input


I'm trying to make an R shiny app that allows you to select a group (gender, age, ethnicity, etc) then displays the histograms of risk scores in a facet_wrap for each level in that group. For example if gender was selected as the group the histogram would have a facet for male and female. In my code below it is not producing any facets.

library(shiny)
library(ggplot2)
# Define UI for miles per gallon app ----
ui <- fluidPage(

  # Application title
  titlePanel("Group fairness analysis"),

  # Sidebar 
  sidebarLayout(
    sidebarPanel(
      selectInput("group", "Group:", 
                  c("Age" = "age",
                    "Gender" = "gender",
                    "Region" = "region",
                    "Ethnicity"="ethnicity"))
      ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
)

# Define server logic----
server <- function(input, output) {

  output$distPlot <- renderPlot({   
  gg <- ggplot(df, aes(x=score))+
      geom_histogram(breaks=seq(0,100,10))+
      facet_wrap(~input$group)
      gg

  })

}

shinyApp(ui, server)

Solution

  • It doesn't work because input$group is character-type, whereas facet_wrap requires a quoted variable.

    Simply solve it by quoting it with get :

    gg <- ggplot(df, aes(x=score))+
          geom_histogram(breaks=seq(0,100,10))+
          facet_wrap(~get(input$group))
    

    Hope this helps!