Home > Net >  How do you use the reactive input as one of the axis of a plot in Shiny
How do you use the reactive input as one of the axis of a plot in Shiny

Time:11-30

Im having trouble using the input$measurement as the y axis so that I can change what data is shown.

This is my code so far

library(dplyr)
library(ggplot2)
library(shiny)
library(shinyWidgets)

mtcars$cars <- rownames(mtcars)
c <- colnames(mtcars)


ui <- fluidPage(
  titlePanel("Car comparisons"),
  selectInput("measurement", "Select Measurement", choices = c, selected = "mpg"),
  selectInput("car", "Select Car", choices = mtcars$cars, multiple=TRUE),
  plotOutput("plot")
  
)

server <- function(input, output, session) {
  
  data <- reactive({
    mtcars %>%
      filter(
        input$measurement %in% c,
        mtcars$cars %in% input$car
      )
  })
  
  output$plot <- renderPlot({
    req(input$measurement, input$car)
    
    data() %>% lapply(input$measurement, 
                 function(x) ggplot(aes(mtcars[,x]))  
                   geom_bar(stat="identity", fill="pink"))
  })
}

shinyApp(ui = ui, server = server)`

It works when I change the current ggplot to ggplot(aes(y=mpg, x=cars)) but I want to be able to change the value that is shown.

CodePudding user response:

You don't need to use lapply here, you can put the input$measurement variable in aes, but need to wrap it to turn it into an expression (or use the deprecated aes_string):

server <- function(input, output, session) {
  
  data <- reactive({
    mtcars %>%
      filter(
        input$measurement %in% c,
        mtcars$cars %in% input$car
      )
  })
  
  output$plot <- renderPlot({
    req(input$measurement, input$car)
    data() %>% ggplot(aes(cars, !!rlang::parse_expr(input$measurement)))  
                        geom_bar(stat="identity", fill="pink")
  })
}
  • Related