0

I have a swimlane plot which I want to order by a group variable. I was also wondering if it is possible to label the groups on the ggplot.

Here is the code to create the data set and plot the data

dataset <- data.frame(subject = c("1002", "1002", "1002", "1002", "10034","10034","10034","10034","10054","10054","10054","1003","1003","1003","1003"),
                      exdose = c(5,10,20,5,5,10,20,20,5,10,20,5,20,10,5),
                      p=     c(1,2,3,4,1,2,3,4,1,2,3,1,2,3,4), 
                      diff = c(3,3,9,7,3,3,4,5,3,5,6,3,5,6,7),
                      group =c("grp1","grp1","grp1","grp1","grp2","grp2","grp2","grp2","grp1","grp1","grp1","grp2","grp2","grp2","grp2")
)


ggplot(dataset, aes(x = diff + 1, y = subject, group = p)) +
  geom_col(aes(fill = as.factor(exdose)), position = position_stack(reverse = TRUE)) 

I want the y axis order by group and I want a label on the side to label the groups if possible

enter image description here

you can see from the plot it is ordered by subject number but I want it ordered by group and some indicator of group.

I tried reorder but I was unsuccessful in getting the desired plot.

APP
  • 25
  • 4
  • Probably the easiest approach would be to facet by `group`, e.g. `+ facet_wrap(~group, ncol = 1, scales = "free_y")`. – stefan Nov 09 '22 at 09:24

1 Answers1

0

As Stefan points out, facets are probably the way to go here, but you can use them with subtle theme tweaks to make it look as though you have just added a grouping variable on the y axis:

library(tidyverse)

dataset %>%
  mutate(group = factor(group),
         subject = reorder(subject, as.numeric(group)),
         exdose = factor(exdose)) %>%
  ggplot(aes(x = diff + 1, y = subject, group = p)) +
  geom_col(aes(fill = exdose), color = "gray50",
           position = position_stack(reverse = TRUE)) +
  scale_y_discrete(expand = c(0.1, 0.4)) +
  scale_fill_brewer(palette = "Set2") +
  facet_grid(group ~ ., scales = "free_y", switch = "y") +
  theme_minimal(base_size = 16) +
  theme(strip.background = element_rect(color = "gray"),
        strip.text = element_text(face = 2),
        panel.spacing.y = unit(0, "mm"),
        panel.background = element_rect(fill = "#f9f8f6", color = NA))

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87