Home > Software engineering >  Display facet based on users selection in shinyApp
Display facet based on users selection in shinyApp

Time:05-19

I want my shinyApp to display facets based on the user selection of a variable.

The function that I've wrote works in base R, but my shinyApp is not displaying any plot when selecting the variables. Also, I've checked similar posts, which I've followed but my app is still not working and I don't know why.

Here is the RepEx.

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectInput("p","p", choices = names(diamonds)),
  selectInput("q","q", choices = names(diamonds)),
  plotOutput("myplot"))

server <- function(input, output, session) {
  
  data <- reactive(diamonds)
  p <- reactive({input$p})
  q <- reactive({input$q})
  
  draw_boxplot <- function(data, p, q){
    ggplot(data=data(), aes(x=cut, y = .data[[p]])) 
      geom_boxplot()   
      facet_wrap(~get(input$q)) #facet_grid(~get(input$Select_unit))
  }
      
  plot1 <- reactive({
    req(data(), input$p, input$q)
    draw_boxplot(data(), p(), q())
  })
  
  output$myplot <- renderPlot({
    plot1()
  })

}

shinyApp(ui, server)

CodePudding user response:

Man, based on what i understood about your need i wrote a simplier code to achieve the output you described. Theres no need to create the function you made. You can insert input values directly in ggplot using aes_string.

library(shiny)
library(ggplot2)

ui <- fluidPage(
        selectInput("p",
                    "p", 
                    selected = "carat",
                    choices = colnames(diamonds)),
        selectInput("q",
                    "q", 
                    selected = "color",
                    choices = colnames(diamonds)),
        plotOutput("myplot"))

server <- function(input, output) {
        
        output$myplot <- renderPlot({
                ggplot() 
                        geom_boxplot(data=diamonds,
                                aes_string(x = "cut", y = input$p))  
                        facet_wrap(~get(input$q))
        })
        
}

shinyApp(ui, server)

enter image description here

CodePudding user response:

Your app is functioning, but it takes ~20 seconds for the plot to load.

Second, input values are inherently reactive, so including them within a render will cause the code within to update.

Here I believe I have the exact same app as above, but much more simple.

library(shiny)
library(ggplot2)

ui <- fluidPage(
  selectInput("p","p", choices = names(diamonds)),
  selectInput("q","q", choices = names(diamonds)),
  plotOutput("myplot"))

server <- function(input, output, session) {
  
  output$myplot <- renderPlot({
    ggplot(data=diamonds, aes(x=cut, y = input$p)) 
      geom_boxplot()   
      facet_wrap(input$q)
    })
  
}

shinyApp(ui, server)

Edit: As Lucca showed in his example, incorporating a selected into the inputs as well as aes_string is probably the best way to go.

  • Related