具有三个因素的 R 条形图

问题描述 投票:0回答:1

我想结合三个因素的信息,但无法解决。

型号: 最低工作代码涵盖模块 A 和 B 的课程,由具有不同教育水平的男性和女性参加。 实现了每个模块的教育水平条形图(见下文)

鉴于生成的条形图,我想在每个教育条形中再次填写性别;这可能吗?

module<-as.factor(c(rep("A",5), rep( "B",6)))
gender<-as.factor(c(rep("female",2), rep("male",3), rep("female",3), rep("male",3)))
# primary, secondary tertiary
edu<-as.factor(c("prim", "sec", "tert", "prim", "sec", "tert","prim", "sec", "tert","prim", "sec"))
course<-data.frame(module, gender, edu)

library(ggplot2)
bar_edu<-ggplot(course, aes(module, fill=edu))
bar_edu+geom_bar(position="dodge")
r bar-chart factors
1个回答
0
投票

实现此目的的一种方法是使用

ggplot2::facet_grid()
:

ggplot(course, aes(x = gender, fill = edu)) + 
  geom_bar(position = "stack") + 
  scale_x_discrete(labels = rep(c("Female", "Male"), 2)) +
  facet_grid(. ~ module, scales = "free_x", space = "free_x", switch = "x") +
  scale_fill_manual(values = c("#f69632", "#56B4E9", "#009E73"),
                    labels = c("Primary", "Secondary", "Tertiary")) +
  labs(title = "Education Level by Module and Gender", 
       x = "Module and Gender", 
       y = "Count", 
       fill = "Education\nLevel") +
  coord_cartesian(expand = FALSE) +
  theme(panel.background = element_blank(),
        axis.line = element_blank(),
        title = element_text(size = 10),
        strip.background = element_blank(),
        strip.placement = "outside",
        strip.text.x = element_text(size = 8, face = "bold"))

1

© www.soinside.com 2019 - 2024. All rights reserved.