Create filtered and interactive boxplot in R Shiny

Viewed 16

This is the code I have so far

library(shiny)
NJData <- data.frame("Year" = c(2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003), 
"WUCode" = c("IR", "PS", "IR", "PS","IR", "PS","IR", "PS"), Annual.Value" = c(12, 14, 
19, 7, 11, 13, 20, 17))

ui <- fluidPage(
  titlePanel("Subsetting Dataset"),
  sidebarLayout(
    sidebarPanel(
      selectInput("codeInput1", label = "Choose Year", choices = unique(NJData$Year)),
      selectInput("codeInput2", label = "Choose WU Type", choices = unique(NJData$WUCode))
     ),
    mainPanel(
      tableOutput("view")
    )
  )
)

server <- function(input, output) {


  dataset <- reactive({
    return(subset(NJData, (Year == input$codeInput1 & Water.Use.Subtype.Code == 
input$codeInput2)))
  })


   #output$view <- renderTable(dataset())

 output$plot <- renderPlot({
   p<-ggplot(dataset(),
          aes_string(
            x       = dataset()$Year,
            y       = dataset()$Annual.Value,
            fill    = dataset()$Year # let type determine plotting
          )
    )
  })
}

shinyApp(ui = ui, server = server)

I want to allow the user to choose what year and what WU type to use and then generate a boxplot of the Annual Value for that year and WU type, but I can't get the boxplot to generate.

Any help is greatly appreciated!

1 Answers

You have to add the type of chart you would like to use in ggplot2, in your case I guess that would be:

ggplot(...) + geom_boxplot()

Here is a refined version of your code:

library(shiny)
library(ggplot2)

NJData <- data.frame(
  "Year" = c(2000, 2000, 2001, 2001, 2002, 2002, 2003, 2003),
  "WUCode" = c("IR", "PS", "IR", "PS","IR", "PS","IR", "PS"),
  "Annual.Value" = c(12, 14, 19, 7, 11, 13, 20, 17)
  )

ui <- fluidPage(
  titlePanel("Subsetting Dataset"),
  sidebarLayout(
    sidebarPanel(
      selectInput("codeInput1", label = "Choose Year", choices = unique(NJData$Year)),
      selectInput("codeInput2", label = "Choose WU Type", choices = unique(NJData$WUCode))
     ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {

  dataset <- reactive({
    subset(
      NJData,
      (Year == input$codeInput1 & WUCode == input$codeInput2)
    )
  })

  output$plot <- renderPlot({
    ggplot(
      dataset(),
      aes_string(
        x = "Year",
        y = "Annual.Value",
        fill = "Year"
      )
    ) + geom_boxplot()
  })

}

shinyApp(ui = ui, server = server)

Related