首页 > 解决方案 > How to create grouped bar plot instead of facet_wrap in R?

问题描述

I have a dataset that has three categorical variables. I know how to use ggplot geom_bar to create a bar plot and facet_wrap. But I want the bars to be grouped by the third categorical variable rather than wrapped. See the plot below. I want the "fall" and "winter" facets to be on top of each other. For example, I want the "fall" results in Grade 10 to be below the "winter" results within one grid. Perhaps I need to structure my data differently.

tmp = data.frame(Grade = rep(1:10, each = 6),
                 Placement = as.factor(rep(1:5, times = 6)),
                 Window = rep(c("fall", "winter"), times = 15),
                 Percent = rnorm(n = 30, mean = 20))

ggplot(data = tmp, 
       aes(x = Grade, y = Percent, fill = Placement)) +
  geom_bar(stat = "identity") +
  facet_wrap(vars(Window)) +
 coord_flip() +
  scale_x_continuous(name = "Grade",
                     breaks = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) + 
  scale_y_continuous(name = "Percent",
                     limits = c(0, 100))

enter image description here

I'd like it to look more like this:

enter image description here

标签: rggplot2

解决方案


This is different than what you had, but much closer to the picture you showed:

ggplot(data = tmp, 
       aes(x = Window, y = Percent, fill = Placement)) +
  geom_bar(stat= "identity",position = "fill") +
  facet_wrap(~Grade, scales = "free_y", switch = "y", nrow = 10) +
  coord_flip() +
  scale_y_continuous(labels = scales::percent, expand = c(0,0))

推荐阅读