Home > Net >  Reactive version of data in Shiny ggplot chart
Reactive version of data in Shiny ggplot chart

Time:10-04

I have data called df that looks like this

Year Major          Grade
2015 Economics        5
2015 Architecture     4
2015 Psychology       4
2016 Economics        4
2016 Architecture     5
2016 Psychology       4
2017 Economics        5
2017 Architecture     5
2017 Psychology       4

I'm interested in making a Shiny R app with a single line chart of Grade by Year, along with a selectInput button to select the major. I think I need to create a reactive version of df to reactively apply the filter, but I'm not sure how.

Here's my code:

df = data.frame(
  Year = c('2015', '2015', '2015', '2016', '2016', '2016', '2017', '2017', '2017'),
  Major = rep(c('Economics', 'Architecture', 'Psychology'), times = 3),
  Grade = c(5,4,4,4,5,4,5,5,4))

ui <- fluidPage(
  inputId = 'MajorSelect',
  selectInput(inputId = "Major", label = "Major", choices = df$Major),
  plotOutput("plot")
  )

server <- function(input, output, session){

  df = reactive({df %>% dplyr::filter(Major == input$MajorSelect)})
  
  output$plot = renderPlot(
    ggplot(data = df(), aes(x = Year, y = Grade, group = Major, color = Major))  
      geom_line())
}

shinyApp(ui, server)

CodePudding user response:

There are some minor issues with your code. First, as you named your original dataset df use a different name for the reactive, e.g. df_filtered (and of course use this name in the ggplot code as well). Second, as the inputId for the selectInput is Major use input$Major in the filter statement. Finally, instead of using df$Major for the choices argument of the selectInput I would suggest to wrap inside unique().

library(shiny)
library(dplyr, warn = FALSE)
library(ggplot2)

ui <- fluidPage(
  selectInput(inputId = "Major", label = "Major", choices = unique(df$Major)),
  plotOutput("plot")
)

server <- function(input, output, session){
  
  df_filtered = reactive({
    df %>% dplyr::filter(Major == input$Major)
  })
  
  output$plot = renderPlot(
    ggplot(data = df_filtered(), aes(x = Year, y = Grade, group = Major, color = Major))  
      geom_line())
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:7815

  • Related