【问题标题】:Shiny input variable directly in ggplot aes (RMarkdown flexdashboard)直接在 ggplot aes 中闪亮的输入变量(RMarkdown flexdashboard)
【发布时间】:2020-04-14 18:49:21
【问题描述】:

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

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

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

【问题讨论】:

  • 另一个建议。您创建的 mtcars_r 对象在这里不是必需的,当多个输出依赖于转换并且您不想多次执行该转换时,反应对象很有用。在您的情况下,在 rective({}) 调用中,您没有对 mtcars 数据框执行任何操作,而我希望您使用响应式输入来执行某些操作。看看这个post,看看我的意思。

标签: r ggplot2 shiny r-markdown flexdashboard


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2020-02-23
    • 2018-06-21
    • 2019-10-09
    • 2019-11-29
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    相关资源
    最近更新 更多