Manuel Popp
Manuel Popp

Reputation: 1185

How can I rotate a complete facet_wrap ggplot?

I applied facet_wrap to a barchart where the groups are different layers/ segments of a vertical profile. It makes sense to plot them on top of each other instead of beside each other. In other words, I want a facet_wrap barplot where the respective boxes are rotated by 90° and plotted vertically on top of each other.

I tried using coord_flip, which, however, only flips the coords in the facets and not the whole boxes.

dat <- as.data.frame(
  cbind(
    c("Layer 1", "Layer 1", "Layer 1", "Layer 2", "Layer 2", "Layer 2", "Layer 3", "Layer 3", "Layer 3"),
    c("group 1", "group 2", "group 3", "group 1", "group 2", "group 3", "group 1", "group 2", "group 3"),
    c(2, 3, 6, 3, 4, 5, 4, 2, 3)
  )
)
names(dat) <- c("ID", "Group", "Value")

ggplot(data = dat) +
  geom_bar(mapping = aes(x= ID, y= Value, fill = "red", group = Group), stat="identity", position = "dodge") +
  labs(title= "", x= "", y = "Value") +
  theme(legend.position="bottom") +
  facet_wrap(~ ID,scales="free")

enter image description here

Upvotes: 1

Views: 1931

Answers (1)

Mossa
Mossa

Reputation: 1718

Nice example. Here's a version of this

dat %>%  
  mutate(Group = factor(Group, levels = rev(levels(Group)))) %>% 
  ggplot() +
  geom_col(
    mapping = aes(
      x = Group,
      y = Value,
      fill = "red",
      group = Group
    ),
    stat = "identity",
    position = "dodge"
  ) +
  labs(title = "", x = "", y = "Value") +
  theme(legend.position = "bottom") +
  facet_grid(ID ~ ., scales = "free_y") +
  coord_flip()

The geom_col has the barcharts in which you can specify both axis. I reordered the Group variable, so that they appear in order.

Result from suggestion

Upvotes: 1

Related Questions