Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
  })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading