teunbrand / ggh4x

ggplot extension: options for tailored facets, multiple colourscales and miscellaneous
https://teunbrand.github.io/ggh4x/
Other
541 stars 33 forks source link

Merging panels in low hierarchy #30

Closed adeben1 closed 3 years ago

adeben1 commented 3 years ago

When using facet_nested(), is there a way to merge the panels of low hierarchy variables? With the purpose of, for instance, setting panel.spacing parameter in a way that only affects higher order variables in the hierarchy defined in facet_nested() or removing borders between low hierarchy variables.

I attach an example.

data <- data.frame(a <- sample(c("A", "B"), 30, replace = T), 
                   b <- sample(c("X", "Y"), 30, replace = T), 
                   c <- sample(c("good", "bad"), 30, replace=T))
colnames(data) <- c("a", "b", "c")

p <- ggplot(data=data, aes(x=a, y=c)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.y=element_blank(), axis.ticks=element_blank(), panel.grid.major=element_blank())

p + facet_nested(c ~ a + b)

preguntagit

I edited the picture. Now panels of "A" and "B" as a function of "bad" and "good" are merged and it could be possible to delete borders and spacing between "X" and "Y" inside those panels. Selection_101

teunbrand commented 3 years ago

Hello there,

No it is currently not possible to merge panels; these are somewhat of a building block in terms of facetting. There are other options however, which I'll illustrate below.

One option is to use guide_axis_nested() in conjuction with interaction() to illustrate within-panel hierarchies. It might be a little bit finicky to get the interaction() right for more complicated cases, but you could also fix this before passing data to ggplot2. If you drop the inner facet specification, you'll get something like this:

library(ggh4x)
#> Loading required package: ggplot2

data <- data.frame(a = sample(c("A", "B"), 30, replace = T), 
                   b = sample(c("X", "Y"), 30, replace = T), 
                   c = sample(c("good", "bad"), 30, replace=T))

ggplot(data, aes(interaction(a, b), c)) +
  geom_point() +
  facet_grid(c ~ a) +
  guides(x = guide_axis_nested())

The second option is to manually set the panel spacing such that inner facets appear merged. This does not work very elegantly with panel borders though!

ggplot(data, aes(a, c)) +
  geom_point() +
  facet_nested(c ~ a + b) +
  theme(
    panel.spacing.x = unit(c(0,5,0), "pt")
  )

Created on 2020-12-07 by the reprex package (v0.3.0)