在R中组合分组和堆积条形图

时间:2017-07-12 10:53:11

标签: r ggplot2 bar-chart stacked-chart

以下是我的数据框架的样子:

CatA    CatB   CatC 
1        Y      A
1        N      B
1        Y      C
2        Y      A
3        N      B
2        N      C 
3        Y      A
4        Y      B
4        N      C 
5        N      A
5        Y      B

我希望在X轴上使用CatA,并且它依靠Y轴。这个图很好。但是,我想为CatB创建组并将其与CatC堆叠,并在Y轴上保持计数。这就是我所尝试的,这就是它的外观:

enter image description here

我希望它看起来像这样:

enter image description here

我的代码:

ggplot(data, aes(factor(data$catA), data$catB, fill = data$catC)) 
+ geom_bar(stat="identity", position = "stack") 
+ theme_bw() + facet_grid( ~ data$catC)

PS:我很抱歉提供图片链接,因为我无法上传它,每次我上传时都会在imgur发生错误。

1 个答案:

答案 0 :(得分:3)

你可以使用facets:

df <- data.frame(A = sample(1:5, 30, T), 
                 B = sample(c('Y', 'N'), 30, T), 
                 C = rep(LETTERS[1:3], 10))

ggplot(df) + geom_bar(aes(B, fill = C), position  = 'stack', width = 0.9) + 
  facet_wrap(~A, nrow = 1) + theme(panel.spacing = unit(0, "lines"))

enter image description here