简体   繁体   中英

Problems with reactive ggplot in Shiny

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.

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()
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM