karpfen
karpfen

Reputation: 499

Increasing margins of facet_grid text

I'm trying to make a facet_grid plot as shown in the example below. One of the names of the facets is too long to be displayed correctly, so it gets cut off.

I tried adding a margin around the text to display the full facet name correctly. However, the margin option in element_text only allows me to add horizontal margins - the height of the text fields seems to be fixed. Is there a way I can add vertical margins as well?

library (ggplot2)    

x <- mtcars
x$cyl <- as.factor (x$cyl)
levels (x$cyl) <- c ("a", "b", "this is a very very long name")

ggplot (x, aes (x = mpg, disp)) +
  geom_point () +
  facet_grid (cyl ~ .) +
  theme (strip.text = element_text (margin = margin (30, 5, 30, 5))) # This line should increase the margins

Version info: R 4.0.3, ggplot2 3.3.2

Upvotes: 1

Views: 1418

Answers (2)

Allan Cameron
Allan Cameron

Reputation: 173803

The problem here is that the facet panels all need to be the same size. If you want to keep the overall plot the same size and the text the same size, you simply have run out of room to play with. You can't fit a quart in a pint jug.

I think the most elegant solution is to wrap the text:

levels(x$cyl) <- stringr::str_wrap(levels(x$cyl), width = 20)

ggplot (x, aes (x = mpg, disp)) +
  geom_point () +
  facet_grid (cyl ~ .) +
  theme (strip.text = element_text (margin = margin (30, 5, 30, 5)))

enter image description here

If this doesn't work for you, the other options the common sense ones: facet in the x direction instead of the y direction, or shorten your labels, or shrink the text or increase the resolution of the plot.


EDIT

If you are prepared to have different sizes of facet, you could build the plot as a ggplotGrob, then find the panel whose height you wish to change and specify that as a proportion of the total plot height using "npc" units, like this:

p <- ggplot (x, aes (x = mpg, disp)) +
  geom_point () +
  facet_grid (cyl ~ .) +
  theme (strip.text = element_text (margin = margin (30, 5, 30, 5))) 

b <- ggplotGrob(p)
b$heights[11] <- unit(0.4, "npc")
grid::grid.newpage()
grid::grid.draw(b)

Upvotes: 3

Duck
Duck

Reputation: 39595

One option could be adding space in the text:

library(ggplot2)
#Code
levels (x$cyl) <- c ("a", "b", "this is a very\n very long name")
#Plot
ggplot (x, aes (x = mpg, disp)) +
  geom_point () +
  facet_grid (cyl ~ .) +
  theme (strip.text = element_text(size=9, lineheight=1.5)) 

Output:

enter image description here

Upvotes: 0

Related Questions