4

I have a plot on a white background with grey facets and white facet text:

ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
       aes(x = x, y = y, color = color)) + 
  geom_point() + 
  facet_grid(~color) + 
  theme(panel.background = element_blank(), 
        strip.text = element_text(color = "white", size = 23)) 

enter image description here

My problem is that descenders (p, g, q, j) cross the facet. I would like the strip background to have a margin around the text so that all glyphs in the facet text are always strictly within the facet rectangle. I can add newlines to the facet text color = c("Ap\n", "Ap\n", "B\n", "B\n") but the margin is too excessive (or the lineheight required is too ugly). Is there a ggplot2 solution to this?

Hugh
  • 15,521
  • 12
  • 57
  • 100
  • 1
    I suppose you could fudge `vjust` to something like .8 in your `element_text`, though then you risk bumping into the top of the strip instead... – mathematical.coffee Jul 09 '15 at 00:47

1 Answers1

5

For ggplot v2.2.0 In theme, specify margins in the strip_text element (see here)

# Set text size
size = 26

library(ggplot2)
library(grid)

p = ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
      aes(x = x, y = y, color = color)) + 
      geom_point() + 
      facet_grid(~color) + theme_bw() +
      theme(strip.text = element_text(color = "white", size = size)) 


  p +
  theme(strip.text.x = element_text(margin = margin(.1, 0, .3, 0, "cm")))

Original You could use the ggplot layout to adjust the height of the strip. The height could be set to an absolute height, for instance, unit(1, "cm"), or, as I've done here, set to a height that adjusts to the font size.

Edit: Updating to ggplot2 2.0.0
Further edit: Updating to grid 3.0.0 grid:::unit.list() no longer needed.

# Set text size
size = 26

library(ggplot2)
library(grid)

p = ggplot(data = data.frame(x = rep(1:2, 2), y = rep(1:2,2), color = c("Ap", "Ap", "B", "B")), 
      aes(x = x, y = y, color = color)) + 
      geom_point() + 
      facet_grid(~color) + theme_bw() +
      theme(strip.text = element_text(color = "white", size = size)) 


# Get ggplot grob
g <- ggplotGrob(p)

# Set the relevant height
g$heights[3] = unit(2, "grobheight", textGrob("a", gp=gpar(fontsize = size))) 


grid.newpage()
grid.draw(g)

enter image description here

Community
  • 1
  • 1
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122