我正在 R 中开发交互式 Shiny 仪表板,当未选择特定输入时,我的条形图遇到了问题。
这就是我想要实现的目标:
问题:
当我从性别或种族选择输入中没有选择任何内容(没有特定输入)时,条形图将所有值显示在彼此之上。仅当选择特定输入时(例如,选择“两者”),条形图才看起来正确针对性别或特定种族)。
我是 R 新手,所以任何帮助将不胜感激!!
output$dbs_plot <- renderPlot({
clean_df <- dbs_count
if (!is.null(input$sex_dbs) && input$sex_dbs != "Both") {
clean_df <- clean_df %>%
filter(sex == input$sex_dbs)
}
if (!is.null(input$race_dbs) && input$race_dbs != "All") {
clean_df <- clean_df %>%
filter(race == input$race_dbs)
}
ggplot(clean_df, mapping = aes(x = dbs_surgery_yn, y = perc)) +
geom_bar(stat = "identity") +
geom_text(aes(label = paste0(round(perc, digits = 2), "%"), y = perc),
vjust = -0.5,
color = "black", size = 3, position = position_dodge(width = 0.9)) +
labs(x = "Did you have DBS Surgery?", y = "Count")
})
我需要条形图仅根据输入显示值,并且我需要它进行清理,而不是覆盖所有值
这是您需要的吗?
library(dplyr)
library(shiny)
library(ggplot2)
data <- expand.grid(
race = c("Black", "White"),
sex = c("Male", "Female"),
year = 2015:2020
) |>
mutate(count = sample(30:60, n(), TRUE))
data
#> race sex year count
#> 1 Black Male 2015 59
#> 2 White Male 2015 42
#> 3 Black Female 2015 51
#> 4 White Female 2015 60
#> 5 Black Male 2016 49
#> 6 White Male 2016 52
#> 7 Black Female 2016 30
#> 8 White Female 2016 42
#> 9 Black Male 2017 48
#> 10 White Male 2017 33
#> 11 Black Female 2017 55
#> 12 White Female 2017 43
#> 13 Black Male 2018 39
#> 14 White Male 2018 37
#> 15 Black Female 2018 33
#> 16 White Female 2018 45
#> 17 Black Male 2019 59
#> 18 White Male 2019 53
#> 19 Black Female 2019 45
#> 20 White Female 2019 34
#> 21 Black Male 2020 32
#> 22 White Male 2020 44
#> 23 Black Female 2020 49
#> 24 White Female 2020 42
ui <- fluidPage(
selectizeInput("sex", "Sex", c("Male", "Female", "Both")),
selectizeInput("race", "Race", c("White", "Black", "Both")),
plotOutput("barchar")
)
server <- function(input, output, session) {
to_plot <- reactive({
req(input$sex, input$race)
if(input$sex != "Both") data <- filter(data, sex == input$sex)
if(input$race != "Both") data <- filter(data, race == input$race)
print(data)
data <- summarise(data, count = sum(count), .by = year)
data
})
output$barchar <- renderPlot({
to_plot() |>
ggplot(aes(x = year, y = count)) +
geom_col()
})
}
shinyApp(ui, server)
创建于 2024-07-26,使用 reprex v2.1.0