假设我有两个不同的数据集,按年龄或地区划分销售额。基于它们,我可以准备如下条形图:
age <- data.frame("year" = c(2019, 2020), "age" = c("<30", "30-40", ">40"), "sales" = c(100, 150, 200, 250, 300, 350))
geo <- data.frame("year" = c(2019, 2020), "geo" = c("Europe", "Asia", "America"), "sales" = c(70, 120, 170, 220, 270, 320))
ggplot(age, aes(fill=as.factor(year), x=age, y=sales))+
geom_bar(position="dodge", stat = "identity")
ggplot(geo, aes(fill=as.factor(year), x=geo, y=sales))+
geom_bar(position="dodge", stat = "identity")
现在,我想在反应式 Shiny 仪表板中使用它们,用户可以在其中选择要绘制的数据集。我尝试以下代码:
# Define UI
ui <- fluidPage(
# App title ----
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: ----
selectInput("indicator", "Choose dataset",
c("age", "geo")),
),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot1")
)
)
)
# Define server logic
server <- function(input, output) {
datasetInput <- reactive({
if (input$Indicator == "age"){
ds1 <-age
}
else if (input$Indicator == "geo"){
ds1 <-geo
}
return(ds1)
})
output$plot <- renderPlot({
ggplot(datasetInput(), aes(fill=as.factor(year), x=input$indicator, y=sales))+
geom_bar(position="dodge", stat = "identity")
})
}
# Create Shiny app ----
shinyApp(ui, server)
但是我得到一个空白的仪表板,没有任何反应。代码有什么问题?
答案 0 :(得分:0)
@stefan 已经指出了两个错误。这个答案只是@stefan 已经说过的内容的详细实现。没什么新鲜事。
input$Indicator 和 input$indicator 是两个不同的东西。 R 区分大小写。将其保留在所有位置的指示器或所有位置的指示器。不要混在一起。在这个答案中,我在所有地方都保留了指标。
mainPanel(plotOutput()) 中的输出 ID 是您选择的“plot1”。生成的 HTML ID 是 plot1。但是在服务器下游,您指的是 output$plot ..."plot" id 不存在,因此它无法将输出附加到 HTML 中的正确元素。再次在两个地方保留 plot1 或在两个地方绘图。在这个答案中,我在两个地方都保留了 plot1。
library(shiny)
library(ggplot2)
age <- data.frame("year" = c(2019, 2020), "age" = c("<30", "30-40", ">40"), "sales" = c(100, 150, 200, 250, 300, 350))
geo <- data.frame("year" = c(2019, 2020), "geo" = c("Europe", "Asia", "America"), "sales" = c(70, 120, 170, 220, 270, 320))
# Define UI
ui <- fluidPage(
# App title ----
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
# Input: ----
selectInput("indicator", "Choose dataset",
choices = c("age", "geo"))),
# Main panel for displaying outputs ----
mainPanel(
plotOutput("plot1")
)
)
)
# Define server logic
server <- function(input, output) {
datasetInput <- reactive({
if (input$indicator == "age"){
ds1 <-age
}
else if (input$indicator == "geo"){
ds1 <-geo
}
return(ds1)
})
output$plot1 <- renderPlot({
ggplot(datasetInput(), aes(fill=as.factor(year), x=input$indicator, y=sales))+
geom_bar(position="dodge", stat = "identity")
})
}
# Create Shiny app ----
shinyApp(ui, server)