Home > Net >  Incorporating Shiny app sliders into ggplot graphs
Incorporating Shiny app sliders into ggplot graphs

Time:12-02

I am trying to filter the dataframe that I use for my graph based on the input values from two sliders. I have sliders that select a range for temperature and wind speed in a given NFL game. (Each row of the dataframe is a quarterback's performance in a game along with game weather and QB measurables, so at least two rows per game.) How do I take the output from the sliders and filter the dataframe based on that? For example, how do I filter df$temperature based on the slider with id "z"?

library(shiny)
library(dplyr)
library(ggplot2)
library(tidyr)

df = read.csv("Combined_QB_Game_Data.csv")
df[df == "--"] = NA
df$Passes.Completed = as.double(df$Passes.Completed)
df$Passes.Attempted = as.double(df$Passes.Attempted)
df$Completion.Percentage = as.double(df$Completion.Percentage)
df$Passing.Yards = as.double(df$Passing.Yards)
df$Passing.Yards.Per.Attempt = as.double(df$Passing.Yards.Per.Attempt)
df$TD.Passes = as.double(df$TD.Passes)
df$Sacks = as.double(df$Sacks)

ui = fluidPage(
    titlePanel("QB Performance"),
    sidebarLayout(
        sidebarPanel(
          selectInput(inputId = "x", 
              label = "Options:", 
              choices = c("Ht", "Wt", 
                          "Forty", "Vertical", "BenchReps", 
                          "BroadJump", "Cone", "Shuttle", "Round", "Pick"),
              selected = "Ht"),
  selectInput(inputId = "y",
                      label = "Options2:",
                      choices = c("Passer.Rating","Passes.Completed","Passes.Attempted","Completion.Percentage","Passing.Yards","Passing.Yards.Per.Attempt","TD.Passes","Ints","Sacks"),
                      selected = "Passer.Rating"),
  sliderInput("z", "Tempurature",
                       min = 0, max = 100, value = c(25, 75)),
  sliderInput("a", "Wind",
                       min = 0, max = 30, value = c(5, 25))
        ),
        mainPanel(
            plotOutput(outputId = "scatterplot")
        )
    )
)

server = function(input, output) {
    output$scatterplot = renderPlot({
        p = ggplot(data = df)  
            aes_string(x = input$x, y = input$y)  
            geom_point() 
          geom_smooth(method = "lm")
        plot(p)
    })
}

shinyApp(ui, server)

CodePudding user response:

One possibility is to treat the data in a reactive conductor:

ggdata <- reactive({
  bounds <- input$z
  df %>% filter(temperature > bounds[1], temperature < bounds[2])
})

and then use it in the renderPlot:

    output$scatterplot = renderPlot({
        ggplot(data = ggdata())  
            aes_string(x = input$x, y = input$y)  
            geom_point()  
            geom_smooth(method = "lm")
    })
  • Related