将条形图堆叠在已分组和未分组的图中

时间:2018-08-02 19:37:12

标签: r ggplot2 stacked-chart

有人已经解释了条形图here中的堆叠条形图

test <- data.frame(person = c("group 1", "group 2", "group 3"), 
                   value1 = c(100, 150, 120),  # male   
                   value2 = c(25, 30, 45) ,    # female
                   value3 = c(25, 30, 45),     # male
                   value4 = c(100, 120, 150),  # female
                   value5 = c(10, 12, 15),     # male
                   value6 = c(50, 40, 70))     # female

library(reshape2) # for melt

melted <- melt(test, "person")

melted$cat <- ''
melted[melted$variable == 'value1' | melted$variable == 'value2',]$cat <- "sub group 1"
melted[melted$variable == 'value3' | melted$variable == 'value4',]$cat <- "sub group 2"
melted[melted$variable == 'value5' | melted$variable == 'value6',]$cat <- "sub group 3"
melted$gender <- ''
melted[melted$variable %in% sprintf("value%i",c(1,3,5)),]$gender <- "female"
melted[melted$variable %in% sprintf("value%i",c(2,4,6)),]$gender <- "male"


p = ggplot(melted, aes(x = cat, y = value, fill = gender)) 

p + 
  geom_bar(stat = 'identity', position = 'stack') +   
  facet_grid(~ person) + 
  scale_fill_manual(values = c("orangered","dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

我想添加另一个组,但该组中没有子组。 ggplot2中有什么命令或功能可以做到吗?

谢谢

1 个答案:

答案 0 :(得分:3)

假设所有内容都集中在一个数据集中,则可以在facet_grid()行中仅添加少量代码就可以重复使用当前代码:

melted2 <- rbind(melted,
                 data.frame(person = rep("group 4", times = 2),
                            variable = NA,
                            value = c(80, 20),
                            cat = "no subgroup",
                            gender = c("female", "male")))    

ggplot(melted2, 
       aes(x = cat, y = value, fill = gender)) + 
  geom_col(position = 'stack') +   # geom_col() is equivalent to geom_bar(stat = "identity")
  facet_grid(~ person, scales = "free_x", space = "free_x") +
  scale_fill_manual(values = c("orangered", "dodgerblue2")) + 
  theme(panel.background = element_rect(fill = 'white'))

plot

scales = "free_x"告诉每个构面仅显示出现在该构面中的cat值。 space = "free_x"相应地调整每个构面的大小,以便所有条形都具有相同的宽度。