Home > Back-end >  Problems with reactive ggplot in Shiny
Problems with reactive ggplot in Shiny

Time:06-28

I have the following data frame

> dput(df)
structure(list(Species = structure(c(2L, 2L, 5L, 5L, 2L, 2L, 
2L, 2L, 5L, 5L, 2L, 2L, 2L, 2L, 2L, 5L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 5L, 2L, 2L, 2L, 2L, 2L, 5L, 2L, 2L, 2L, 5L, 
2L, 5L, 2L, 2L, 5L, 2L, 2L, 2L, 2L, 2L, 2L, 5L, 2L, 2L, 2L), .Label = c("Blue tit", "Coal tit", "Great tit", "Marsh tit"
), class = "factor"), Clutch.size = c(9L, 10L, 9L, 6L, 10L, 10L, 
10L, 9L, 7L, 8L, 9L, 9L, 10L, 8L, 10L, 10L, 9L, 8L, 8L, 8L, 8L, 
9L, 10L, 7L, 11L, 10L, 11L, 6L, 6L, 9L, 8L, 8L, 8L, 8L, 9L, 10L, 
9L, 8L, 9L, 9L, 8L, 7L, 8L, 9L, 9L, 7L, 9L, 10L, 7L, 7L, 8L, 
10L, 12L)), row.names = c(NA, -53L), class = "data.frame")
> 

I am playing around with shiny to try and make some interactive plots. For example I have tried to make a simple boxplot where you can plot species and their clutch sizes. Using the code below

library(shiny)
library(tidyverse)


ui <- fluidPage(
  selectInput(inputId = "species", label = "Choose Species", #make an input to display mean clutch size per species
             c("Blue tit", "Great tit", " Marsh tit", "Coal tit")), #give the options
  plotOutput("csboxplot")
  
)





server <- function(input, output) {
  
output$csboxplot <-renderPlot(
 { 
   df %>%
    ggplot(aes(x = input$species, y = Clutch.size))  
    geom_boxplot()
 })

}

# Run the application 
shinyApp(ui = ui, server = server) 

However when I change the species on the selectInput box on the shiny app page it displays the same data every time. I'm not sure how I fix this?

You can ignore the simplicity of the plot this is just for illustrating the issue.

CodePudding user response:

You have to filter your data for the selected Species:

library(shiny)
library(tidyverse)

ui <- fluidPage(
  selectInput(
    inputId = "species", label = "Choose Species", # make an input to display mean clutch size per species
    c("Blue tit", "Great tit", " Marsh tit", "Coal tit")
  ), # give the options
  plotOutput("csboxplot")
)

server <- function(input, output) {
  output$csboxplot <- renderPlot({
    df %>%
      filter(Species %in% input$species) %>%
      ggplot(aes(x = Species, y = Clutch.size))  
      geom_boxplot()
  })
}
  • Related