Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

r - How to display strip labels below the plot when faceting?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...