【问题标题】:Multiple variables to facet_wrap from selectInput: R Shiny从 selectInput 到 facet_wrap 的多个变量:R Shiny
【发布时间】:2021-08-11 09:19:59
【问题描述】:

我正在使用 facet_wrap() 为我的 Shiny App 寻求帮助。我有一些数据,我希望应用程序使用从单个 selectInput 中选择的一个或多个变量动态 facet_wrap。应用程序只使用一个变量而不是多个变量。当我从同一个 selectInput 中选择多个变量时,图中只考虑第一个变量进行分面。我不想使用 facet_grid()。 有两件事我需要帮助。

  1. 当应用程序首次启动时,我收到错误“错误:第一个参数无效”。如何摆脱这个错误。
  2. 如何使用从单个 selectInput 中选择的多个变量来刻面图。 非常感谢任何建议或帮助。

重复代码:

library(shiny)
library(tidyverse)
library(DT)
# Define UI for data upload app ----
ui <- fluidPage(
    titlePanel("Upload & View Files"),
      sidebarLayout(
        sidebarPanel(width = 2,
          selectInput("facet", "Select Facets", choices = colnames(data), "", multiple = T)
  ),
    
    # Main panel for displaying outputs ----
    mainPanel("Data View",
      plotOutput("heatmap", width = "1050px", height = "800px"),
      DT::dataTableOutput("table")
      
    )
    
  )
)

# Define server logic to read selected file ----
server <- function(session, input, output) {
  data <- diamonds
   output$table  <- DT::renderDataTable(data, options = list(paging = T, pageLength = 20))
   output$heatmap <- renderPlot({
     ggplot(data, aes(x = carat, fill = carat)) + geom_bar() + facet_wrap(~ get(input$facet), scales = "free")
   })
  }
shinyApp(ui, server)

我看到的是从 selectInput 中选择多个变量时;例如:切割、清晰度、深度等。就像拥有facet_wrap(~ cut + clarity + depth, scales = "free)

Error Message Multiple Facet required

【问题讨论】:

    标签: r shiny facet-wrap selectinput


    【解决方案1】:

    要消除错误,请使用req()。对于多个选定的变量,一种方法如下所示。可能有更好的方法。

    output$heatmap <- renderPlot({
        req(input$facet)
        
        facets <- input$facet %>% 
          str_replace_all(",", "+") %>% 
          rlang::parse_exprs()
        
        ggplot(data, aes(x = carat, fill = carat)) + geom_bar() +
          facet_wrap(vars(!!!facets), scales = "free")
        
      })
    

    【讨论】:

    • 您好 YBS,感谢您的回复。它确实按我需要的方式工作。欣赏它。
    • 接受已回答您的 OP 的答案被认为是礼貌的。这有助于其他正在寻找相同/相似查询解决方案的人。此外,人们可能愿意在您未来的查询中为您提供帮助。
    猜你喜欢
    • 2018-06-22
    • 2019-03-04
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2020-09-02
    相关资源
    最近更新 更多