edit strip size ggplot2
Asked Answered
D

2

19

I have tried to apply this solution (How can I change the size of the strip on facets in a ggplot?1) to change the size of the strip on facets in a ggplot, I have increase the height size

library(ggplot2)
library(gtable)

d <- ggplot(mtcars, aes(x=gear)) + 
            geom_bar(aes(y=gear), stat="identity", position="dodge") +
            facet_wrap(~cyl)

g <- ggplotGrob(d)
g$heights[[3]] = unit(5,"in")

grid.newpage()
grid.draw(g)

This is what I get, it does only increase the space (white) on the top of the strip: enter image description here

Why does it work differently?

Dekeles answered 2/1, 2017 at 14:6 Comment(1)
Newer versions of ggplot2 have an overhauled facet system, which is why this no longer works.Martella
W
38

A simple solution is to specify the margins of your strip.text elements appropriately:

ggplot(mtcars, aes(x=gear)) + 
  geom_bar(aes(y=gear), stat="identity", position="dodge") +
  facet_wrap(~cyl) + 
  theme(strip.text.x = element_text(margin = margin(2,0,2,0, "cm")))

enter image description here

Waine answered 2/1, 2017 at 14:52 Comment(0)
M
3

Something like this seems to work:

g$heights[[6]] <- unit(5,"in")
g$grobs[[17]]$heights <- unit(2,"in")
g$grobs[[18]]$heights <- unit(2,"in")
g$grobs[[19]]$heights <- unit(2,"in")

grid.newpage()
grid.draw(g)

Note that looking at g$grobs tells us grobs 17, 18 and 19 are the strips.

You can automate the second step with:

index <- which(sapply(g$grobs, function(x) x$name == "strip"))
g$grobs <- lapply(seq_along(g$grobs), function(.x) {
  if(.x %in% index) {
    g$grobs[[.x]]$heights <- unit(2,"in")
  } 
  g$grobs[[.x]]
} )

enter image description here

Martella answered 2/1, 2017 at 14:26 Comment(3)
Thanks. So, basically g$heights[[6]] <- unit(5,"in") moves the strip, while g$grobs[[17]]$heights <- unit(2,"in") enlarges strip area. But I can not see the correlation between unitsDekeles
That's correct. It seems the units are a bit weird since g$heights[[6]] gives 5cm after assigning inches. I just played around a bit.Martella
there is no [[<- method for grid units. Only recently was one introduced for [<- but it note that it coerces the result to unit.list.Coster

© 2022 - 2024 — McMap. All rights reserved.