代码之家  ›  专栏  ›  技术社区  ›  Tdebeus

带交互式条形图和文本输入的闪亮应用程序

  •  0
  • Tdebeus  · 技术社区  · 7 年前

    我是一个新手,所以在用户界面和服务器之间的对话中遇到了麻烦。我想创建一个 ggplot2 带有动态筛选参数的条形图,因此我可以在 textInput 小部件,这样条形图就改变了。

    数据:

    我正在处理来自300个文档的大约50000个单词,这就是为什么我需要一个文本输入,但这里有一些示例数据:

    library(tidyverse)
    library(shiny)
    
    example_df <- tibble::tribble(
      ~doc,         ~word, ~n,
       "A", "sustainable", 5L,
       "A",    "migrants", 2L,
       "A",    "building", 4L,
       "B", "sustainable", 2L,
       "B",    "together", 1L,
       "B",    "building", 5L
      )
    

    用户界面:

    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          textInput(inputId = "word", 
                    label = "Word:",
                    value = "sustainable"),
        ),
    
        mainPanel(
          plotOutput(outputId = "barchart")
        )
      )
    )
    

    使用此代码,我已经遇到了一个我不理解的错误:

    Error in tag("form", list(...)) : argument is missing, with no default

    服务器:

    server <- function(input, output) {
    
      output$barchart <- renderPlot({
        example_df %>%
          filter(word == input) %>%
          arrange(desc(n)) %>%
          head(20) %>%
          ggplot(aes(x = reorder(doc, n),
                                         y = n)) +
          geom_col() +
          theme_minimal()
      })
    }
    

    我知道这个闪亮的代码可能是疯狂的,但所有的帮助都是非常感谢的!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Chris    7 年前

    您有两个小错误:

    首先:

    sidebarPanel(
          textInput(inputId = "word", 
                    label = "Word:",
                    value = "sustainable"),
        )
    

    您只是有一个额外的尾随逗号,这是不必要的,这也是您得到错误的原因。

    其次:

    example_df %>%
          filter(word == input)
    

    您没有指定要使用的输入。正确的语法是 filter(word == input$word) 其中“word”是您的textInput的ID。

    全部更正的代码:

    library(tidyverse)
    library(shiny)
    
    example_df <- tibble::tribble(
      ~doc,         ~word, ~n,
      "A", "sustainable", 5L,
      "A",    "migrants", 2L,
      "A",    "building", 4L,
      "B", "sustainable", 2L,
      "B",    "together", 1L,
      "B",    "building", 5L
    )
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          textInput(inputId = "word", 
                    label = "Word:",
                    value = "sustainable")
        ),
    
        mainPanel(
          plotOutput(outputId = "barchart")
        )
      )
    )
    
    server <- function(input, output) {
    
      output$barchart <- renderPlot({
        example_df %>%
          filter(word == input$word) %>%
          arrange(desc(n)) %>%
          head(20) %>%
          ggplot(aes(x = reorder(doc, n),
                     y = n)) +
          geom_col() +
          theme_minimal()
      })
    }
    
    
    shinyApp(ui, server)
    
    推荐文章