11

It seems that the strips are always above the plot created by ggplot2. Can they be moved below the plot?

For example:

library(ggplot2) 
qplot(hwy, cty, data = mpg) + facet_grid( . ~ manufacturer)

displays the car information on top. Can they be displayed be at the bottom?

joran
  • 169,992
  • 32
  • 429
  • 468
Max C
  • 2,573
  • 4
  • 23
  • 28
  • 2
    A similar question was asked in ggplot mailing list some time age. [See here](http://groups.google.com/group/ggplot2/browse_thread/thread/415c00e3373c9cc8/8fb65cc4aa0849cf?lnk=gst&q=facet+text+label#8fb65cc4aa0849cf) – Sandy Muspratt Apr 27 '12 at 08:20
  • Thanks!!! I did not realize it was so difficult – Max C May 02 '12 at 01:38
  • See also: http://stackoverflow.com/questions/3261597/can-i-change-the-position-of-the-strip-label-in-ggplot-from-the-top-to-the-botto (another negative answer) – Ben Bolker May 09 '12 at 19:34

1 Answers1

7

Update: Using ggplot2 version 2.1.0, consider using switch = 'x'. See ?facet_grid for details.

Using gtable functions, it is easy to move the strip. (Or see here for anther version - swapping x-axis and strip)

library(ggplot2)
library(gtable)
library(grid)

p <- ggplot(mpg, aes(hwy, cty)) + geom_point() + facet_grid( . ~ manufacturer) +
     theme(strip.text.x = element_text(angle = 90, vjust = 1),
           strip.background = element_rect(fill = NA))

# Convert the plot to a grob
gt <- ggplotGrob(p)

# Get the positions of the panels in the layout: t = top, l = left, ...
panels <-c(subset(gt$layout, grepl("panel", gt$layout$name), select = t:r))

# Add a row below the x-axis tick mark labels,
# the same height as the strip
gt = gtable_add_rows(gt, gt$height[min(panels$t)-1], max(panels$b) + 2)

# Get the strip grob
stripGrob = gtable_filter(gt, "strip-t")

# Insert the strip grob into the new row
gt = gtable_add_grob(gt, stripGrob, t = max(panels$b) + 3, l = min(panels$l), r = max(panels$r))

# remove the old strip
gt = gt[-(min(panels$t)-1), ]

grid.newpage()
grid.draw(gt)

enter image description here

Community
  • 1
  • 1
Sandy Muspratt
  • 31,719
  • 12
  • 116
  • 122
  • 1
    If you're like me and you want the strip labels *above* the x-axis, you can use `gt = gtable_add_grob(gt, stripGrob, t = max(panels$b) + 1, l = min(panels$l), r = max(panels$r))` in place of what Sandy has – Nova Apr 06 '16 at 13:57