我是Shiny的新手,所以在UI和服务器如何相互通信时遇到了麻烦。我想创建一个带有动态过滤器参数的ggplot2
条形图,这样我就可以在textInput
小部件中输入一个单词,这样条形图就会发生变化。
数据:
我正在处理来自 50,000 个文档的 abt 300 个单词,这就是为什么我需要文本输入,但这里有一些示例数据:
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()
})
}
我知道这个闪亮的代码可能很疯狂,但非常感谢所有的帮助!
您有两个小错误:
首先:
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)