直接在 ggplot aes(RMarkdown flexdashboard)中闪亮输入变量

Shiny input variable directly in ggplot aes (RMarkdown flexdashboard)

我正在尝试生成一个交互式绘图,其中 x 轴取决于输入。就像在这个最小的例子中一样,R 只给我一个箱线图(x 轴标记:as.factor(cyl))而不是三个(对于 cyl == 4,6,8)。

如何直接在 aes 的参数中包含 (render/paste) 输入变量,以便获得动态轴?

最小示例:(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()
})
```

这是您应该使用的代码。你缺群审美

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

最小的闪亮示例

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)