Search code examples
rggplot2shinyr-markdownflexdashboard

Shiny input variable directly in ggplot aes (RMarkdown flexdashboard)


I'm trying to produce an interactive plot, where the x-axis depends on input. Like in this minimal example, R just gives me one boxplot (x-axis labelled: as.factor(cyl)) instead of three (for cyl == 4,6,8).

How can I include (render/paste) the input variable directly in the arguments of aes so that I get a dynamic axis?

Minimal example: (Rmd Flexdashboard)

---
title: ""
output: 
  flexdashboard::flex_dashboard:
  orientation: columns
vertical_layout: fill
runtime: shiny
---

Column {.sidebar}
-----------------------------------------------------------------------

### Input

```{r }
radioButtons("xaxis", "x-axis:",
            c("Cly" = "cyl",
              "VS" = "vs"))
```

Column
-----------------------------------------------------------------------   
```{r}
mtcars_r <- reactive({mtcars})

library(ggplot2)

renderPlot({
    ggplot(mtcars_r(), aes_string(x = paste("'as.factor(", input$xaxis, ")'", sep = ""), y = 'wt')) + geom_boxplot()
})
```

Solution

  • This is the code you should use. You are missing the group aesthetic

    renderPlot({
        ggplot(
          mtcars_r(),
          aes_string(x = input$xaxis, y = 'wt', group = input$xaxis) +
          geom_boxplot()
    })
    

    Minimal Shiny example

    library(shiny)
    
    ui <- fluidPage(
      radioButtons("xaxis", "x-axis:",
                   c("Cly" = "cyl",
                     "VS" = "vs")) ,
      plotOutput("plot")
    )
    
    server <- function(input, output, session) {
    
      output$plot <- renderPlot({
        mtcars %>%
          ggplot(aes_string(x = input$xaxis, y = 'wt', group = input$xaxis)) +
          geom_boxplot()
      })
    }
    
    shinyApp(ui, server)