Home > Blockchain >  Having trouble linking the input to my plot output in Rshiny
Having trouble linking the input to my plot output in Rshiny

Time:05-26

I'm creating an Rshiny with two tabs. The data is a list of students, and the plots/tables are to be filtered through the input of grade selection on a drop-down list. The table I have on tab one is working fine, but everything I have tried to do to connect the last two plots on the second tab to the input are not working. Now I have it to where it is just showing totals without using the input filter of grade. Can anyone detail how to connect my input to both output plots? I'll put my code below

library(shiny)
library(tidyverse)

students = read.csv("C:/Users/j062d273/Downloads/RShiny Grade EX.csv",
                    stringsAsFactors = FALSE)


# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    headerPanel("Student Data"),

    # tabs set up
    tabsetPanel(
      tabPanel(title = "Students by Grade",
        mainPanel(width = 12, align = "center",
          selectInput("grade", "Select Grade", choices=unique(sort(students$Grade, 
                decreasing = FALSE)), selected = 1),
                submitButton("Go"),
          tags$h3("Student List"),
          div(style = "border:1px black solid;width:80%",tableOutput("student_list"))
)),
      tabPanel(title = "Trends by Grade",
               mainPanel(width = 12,align = "center",
                         div(style = "float:left;width:36%;",plotOutput("male_fem_dist")),
                         div(style = "float:right;width:64%;",plotOutput("ethnicity_plot")))
    )))
   

# Define server logic required to draw plot
server <- function(input, output) {
  output$student_list <- renderTable({
    gradefilter <- subset(students, students$Grade == input$grade)
  })
  
  output$male_fem_dist <- renderPlot({
    ggplot(students, aes(x=Gender))  
      geom_bar(fill = "blue", color = "red")  
      ggtitle("Gender Count by Selected Grade")
  })
  
  output$ethnicity_plot <- renderPlot({
    ggplot(students, aes(x=Ethnicity))  
      geom_bar(fill = "red", color = "blue")  
      ggtitle("Ethnicity Count by Selected Grade")
  })
    }

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

CodePudding user response:

Filter the dataset first, and then use it in both table and plot.

Try this

server <- function(input, output) {
  gradefilter <- reactive({subset(students, students$Grade == input$grade)})
  
  output$student_list <- renderTable({gradefilter()})
  
  output$male_fem_dist <- renderPlot({
    ggplot(gradefilter(), aes(x=Gender))  
      geom_bar(fill = "blue", color = "red")  
      ggtitle("Gender Count by Selected Grade")
  })
  
  output$ethnicity_plot <- renderPlot({
    ggplot(gradefilter(), aes(x=Ethnicity))  
      geom_bar(fill = "red", color = "blue")  
      ggtitle("Ethnicity Count by Selected Grade")
  })
}
  • Related