ggplot geom_bar 在 x 轴上具有单独的分组变量

ggplot geom_bar with separate grouped variables on the x axis

我有一个包含五 (5) 列数据的数据框。第一个是主要分组(cat1 或 cat 2),其他列变量 V1 到 v4 是特征及其存在(1 = 否,2 = 是)。我想为每个类别和每个变量 V1 到 V4 绘制特征计数的条形图……最好不要更改周围的数据框,但如果需要的话可以。我想从中实现的数据脚本和情节如下。所有变量都是因素。目的是查看哪些特征在 Cat 1 和 Cat 2 中占主导地位。欢迎提供任何指导或链接。

cat = as.factor(c(1,1,1,1,1,2,2,2,2,2))
v1 =  as.factor(c(1,2,2,1,1,2,1,1,1,1))
v2 =  as.factor(c(1,1,2,2,1,1,2,2,1,1))
v3 =  as.factor(c(1,1,1,1,2,2,1,1,2,2))
v4 =  as.factor(c(1,2,2,2,2,1,2,2,1,1))
df = data.frame(cat,v1,v2,v3,v4)

一种方法是重塑数据,计算每个类别中的是和否并绘制:

library(tidyverse)
cust_labeller <- function(x) paste0("Cat = ", x)

df %>%
  pivot_longer(cols = -cat) %>%
  count(cat, name, value) %>%
  mutate(value = recode(value, `1` = 'no', `2` = 'yes')) %>%
  ggplot() + aes(name, n, fill = value) + 
  geom_col(position = 'dodge') + 
  scale_fill_manual(values = c('blue', 'red')) + 
  facet_wrap(.~cat, labeller = as_labeller(cust_labeller),
             strip.position="bottom") 

library(tidyverse)

facet_labeller <- function(string, prefix = "Cat = ") paste0(prefix, string)

df %>%
  pivot_longer(c(v1:v4)) %>%
  mutate(value = fct_recode(value, c(no = "1"), c(yes = "2"))) %>%
  group_by(cat, name, value) %>%
  add_count() %>%
  ggplot(aes(name, n, group = value, fill = value)) +
  geom_bar(stat = "identity", position = position_dodge(.9), show.legend = F) + 
  geom_text(aes(label = value, y = -.1), position = position_dodge(.9)) +
  facet_wrap(~cat, strip.position = "bottom", 
             labeller = as_labeller(facet_labeller)) +
  theme(panel.background = element_blank(), panel.border = element_rect(fill = NA))