teunbrand / ggnomics

A small project to add ggplot2 extensions
https://teunbrand.github.io/ggnomics/
Other
80 stars 4 forks source link

Specify nrow/ncol in facet_nested? #5

Closed jeremymsimon closed 5 years ago

jeremymsimon commented 5 years ago

I have a huge figure (48 outer facets, 2 inner facets, each with 2 parts). If I plot using something like:

tibble %>%
+     mutate(Cluster = fct_relevel(Cluster, unique(tibble$Cluster))) %>%
+     mutate(Genotype = fct_relevel(Genotype, "WT", "mutant")) %>%
+     ggplot(aes(fill = Genotype, x= Genotype, y=Proportion)) +
+     geom_boxplot() +
+     geom_point(pch = 21, position = position_jitterdodge()) +
+     facet_nested(~ Cluster + Timepoint, scales="free") +
+     scale_fill_manual(values=c("skyblue1","darksalmon"))

I get it to work, technically speaking, but all 48 outer facets are all in one row and the plot is unreadable.

Is it possible to implement (or combine with) a facet_wrap(ncol=x,nrow=y) sort of functionality so I can control how many rows or columns of facets there are?

teunbrand commented 5 years ago

Hi, there thanks for bringing this to my attention.

I can see how your example can become unreadable, but I haven't implemented your suggestion for facet_wrap() because that way of facetting can break up a groups of facets over rows/colums that should, ideally, be nested. The facet_nested() is based on facet_grid() which also doesn't have ncol or nrow options.

As a workaround, I might suggest something along the following lines:

library(ggplot2)
library(ggnomics)
library(grid)

dummydata <- expand.grid(Cluster = factor(LETTERS[1:24]), Timepoint = 1:2)
dummydata$x <- rnorm(nrow(dummydata))
dummydata$y <- rnorm(nrow(dummydata))

# Make the following fit your actual data
dummydata$row <- rep(1:4, each = 6)

rows <- split(dummydata, dummydata$row)
rows <- lapply(rows, function(df){
  ggplot(df, aes(x, y)) +
    geom_point() +
    facet_nested(~ droplevels(Cluster) + Timepoint, scales = "free") +
    theme(axis.title.x = element_blank())
})

gt <- rbind(ggplotGrob(rows$`1`),
            ggplotGrob(rows$`2`),
            ggplotGrob(rows$`3`),
            ggplotGrob(rows$`4` + theme(axis.title.x = element_text())),
            size = "last")

grid.newpage(); grid.draw(gt)
teunbrand commented 5 years ago

Closing this issue since I'm not planning on a facet_wrap() version of facet_nested() anytime in the near future.