ggplot 中两个变量的轴标签?

Axis labels for two variables in ggplot?

我有一个包含三个变量的 ggplot:office、level 和 gender。该图应按办公室和级别进行分解,并显示每个办公室的级别和性别代表。我可以按照我想要的方式处理情节,但我无法创建 x 轴文本来显示每个办公室的级别——所有显示在 x-axis 下的都是办公室名称,使得无法区分不同级别的条形图(我用不同颜色处理的性别不是问题,除非有人是色盲......)。我已经编辑了标题、xLab、yLab 等行以专注于该问题。感谢您的帮助!

这是我的数据:

#A tibble: 20 x 4

   office     level   gender     count
 1 office1      A     Female     3
 2 office1      A     Male       1
 3 office1      B     Female     11
 4 office1      B     Male       9
 5 office1      C     Female     16
 6 office1      C     Male       13
 7 office1      C     Other      2
 8 office1      D     Female     16
 9 office1      D     Male       11
10 office1      D     Female     6
11 office1      D     Male       10
12 office1      D     Other      1
13 office2      A     Male       1
14 office2      A     Female     3
15 office2      B     Male       1
16 office2      B     Female     12
17 office2      B     Male       3
18 office2      B     Female     1
19 office2      D     Male       5
20 office2      D     Male       1

这是我的代码:

myBarChart <- function(data,var1,var2,var3,count,factor1, factor2) {
  
# the following code creates the tibble above when I run the function:
  fields <- c(var1,var2,var3)
  data <- df[ ,fields]
  data[[var1]] <- factor(data[[var1]], levels = factor1)
  data[[var2]] <- factor(data[[var2]], levels = factor2)
  data <- data %>% group_by_at(fields) %>% summarize(count = n()) 
  data <- filter(data,count >= 1)
  data <- na.omit(data) %>% 

# here is the plot code and this is where I need help: 
  ggplot(data, aes_string(x=var1, y=count, fill=var3)) +
    geom_bar(stat = 'identity',width=1.25,position = position_dodge2(padding=0.25,reverse=FALSE,preserve=c("single"))) +
    geom_text(aes(label=count),vjust=-.5,position=position_dodge2(width=1.25,preserve="single"),size=2.5) +
    facet_wrap(var1, strip.position="bottom", scales = "free_x", nrow=1)  +

# I was hoping that the code for strip.text.x would give me the values for var2 (the levels) within each office, but it doesn't.
    theme(strip.text.x = element_text(aes(label=data[[var2]]), size=12)) + 
    theme(strip.placement = "outside")

} # end function

# here is how I invoke the function, which runs fine except for the axis labels always reflecting only 'office': 
     myBarChart(data,'office','level','gender',c('office1','office2'),c("A","B","C","D"),'count')

我认为您需要对 x-axis 使用 level,对 y-axis 使用 countoffice 的分面和 [=14 的填充=] ?

像这样:

data %>% 
  ggplot(aes(level, count, fill = gender)) + 
  geom_col(position = position_dodge2(preserve = "single")) + 
  facet_wrap(~office, strip.position = "bottom") + 
  theme(strip.placement = "outside")

结果: