r - 如何在 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))
})
解决方案
我们可以返回一个字符串switch
,然后使用group_by
withacross
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))
})
推荐阅读
- reactjs - 如何使用 react-router-dom 在“x”秒后“重定向到”
- python - 如何在seaborn中增加子图的大小
- javascript - 绕过浏览器 URL 编码以从查询参数中反射 XSS
- html - Googlelabs 暗模式切换
- c++ - 类型检查模板参数的编译器错误
- java - 在每个第 n 个分隔符处拆分,并保留字符
- flutter - 需要访问 2 个集合的 Flutter、Firestore 和 FutureBuilder
- typescript - 如何使用 NavigationHelpersCommon 键入检查 ReactNavigation 的导航?
- sql - 如何将整个列的数据类型从数字转换为雪花中的时间戳
- reactjs - 反应创建自定义事件