首页 > 解决方案 > 如何在 R Shiny 应用程序中创建具有两个反应值的堆积百分比条形图?

问题描述

我正在尝试在 R 中制作具有两个反应值的百分比条形图。下面是我正在使用的代码。我不断收到错误“找不到对象'种族'”和“找不到对象'性别'”。但是,“种族”和“性别”都在数据框“filtered_data()”中。你知道我该如何解决这个问题吗?

这是选项卡面板:

tabPanel(title = "Comparison Bar Plot",
                                                    h1("Bar Chart"),
                                                     h3("Adjust"),
                                                     selectInput(inputId = "AxisX", label = "X Axis Variable",
                                                                 choices = c("Race", "Gender"),
                                                                 selected = "Race"),
                                                     selectInput(inputId = "AxisY", label = "Y Axis Variable",
                                                                 choices = c("Race", "Gender"),
                                                                 selected = "Gender"),
                                                     plotlyOutput("comparisonbarplot")
                                            )

这是输出:

    output$comparisonbarplot <- renderPlotly({
  filtered_data() %>% group_by(switch(input$AxisX, Race=race,Gender=gender), switch(input$AxisY, Race=race,Gender=gender)) %>%
    summarise(count=n()) %>% 
    mutate(perc = count/sum(count)) %>%
    ggplot(aes(x = switch(input$AxisX, Race=race,Gender=gender), y = perc*100, fill=switch(input$AxisY, Race=race,Gender=gender))) +
    scale_fill_manual(values =cbPalette) +
    geom_bar( stat="identity") +
    xlab("Race/Ethnicity") +
    ylab("Percent") +
    labs(title = "Race/Ethnicity and Gender of Defendants \n in Dutchess County Courts Starting Fall 2018", fill = "Gender:")+
    theme_economist() +
    theme(plot.title = element_text(hjust = 0.5))
    })

标签: rshinyshiny-reactivity

解决方案


我们可以返回一个字符串switch,然后使用group_bywithacross

 output$comparisonbarplot <- renderPlotly({
   fstgrp <- switch(input$AxisX, 
                              Race="race",
                              Gender="gender")
   scndgrp <- switch(input$AxisY,
                             Race="race",
                             Gender="gender")
  filtered_data() %>%
         group_by(across(all_of(c(fstgrp, scndgrp)))) %>%
    summarise(count=n()) %>% 
    mutate(perc = count/sum(count)) %>%
    ggplot(aes(x = .data[[fstgrp]], y = perc*100,
        fill=.data[[scndgrp]])) +
    scale_fill_manual(values =cbPalette) +
    geom_bar( stat="identity") +
    xlab("Race/Ethnicity") +
    ylab("Percent") +
    labs(title = "Race/Ethnicity and Gender of Defendants \n in Dutchess County Courts Starting Fall 2018", fill = "Gender:")+
    theme_economist() +
    theme(plot.title = element_text(hjust = 0.5))
    })

推荐阅读