Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display strip labels below the plot when faceting?

Tags:

r

ggplot2

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?

like image 332
Max C Avatar asked Apr 07 '12 22:04

Max C


1 Answers

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

like image 198
Sandy Muspratt Avatar answered Sep 28 '22 04:09

Sandy Muspratt