Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

edit strip size ggplot2

Tags:

r

ggplot2

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?

like image 550
Al14 Avatar asked Jan 02 '17 14:01

Al14


2 Answers

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

like image 93
wici Avatar answered Nov 09 '22 15:11

wici


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

like image 3
Axeman Avatar answered Nov 09 '22 14:11

Axeman