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
700 views
in Technique[技术] by (71.8m points)

r - Flip facet label and x axis with ggplot2

I am looking to flip the labels on a faceted panel of 1 row and 5 columns, so that the facet headers appear on bottom, and the x axis appears on top of facets.

The reason is that I want to reuse those headers for a table that will be directly below the graph.

So in this example...

library(ggplot2)

my.hist<-ggplot(diamonds, aes(clarity)) + geom_bar()

my.hist + facet_wrap( ~ cut, ncol=5) + coord_flip()

I would want the "cut" labels to show up below the chart. I was thinking that facet_grid might hold the key, but is only a guess.

Anyone know how to accomplish this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Getting the facet strips below the plot is easy,

library(gtable)
g <- ggplotGrob(p)

strips <- gtable_filter(g, "strip_t", trim=FALSE)
grid.newpage()
grid.draw(rbind(g, strips[3,], size="first"))

the axes, however, require more care because one has to reverse the position of the tick marks and labels. You can maybe start with this,

tweak_axis <- function(a){
  inner <- a[["children"]]["axis"][[1]]
  inner[["grobs"]] <- rev(inner[["grobs"]])
  inner$grobs[[2]]$y <- inner$grobs[[2]]$y - unit(0.15, "cm")
  a[["children"]]["axis"][[1]] <- inner
  a
}

axes <- gtable_filter(g, "axis_b", trim=FALSE)
axes$grobs <- lapply(axes$grobs, tweak_axis)
grid.newpage()
grid.draw(axes)

Edit: based on the above, a "complete" solution might be

grid.newpage()
g2 <- g
new_axes <- lapply(g2$grobs[grepl("axis_b", g2$layout$name)], tweak_axis)
g$grobs[grepl("strip_t", g$layout$name)] <- new_axes 
g$grobs[grepl("axis_b", g$layout$name)] <- g2$grobs[grepl("strip_t", g2$layout$name)] 
# heights should be changed too, but it's kind of ok here
xlab <- 7; title <- 1:2
grid.draw(rbind(g[xlab,], g[-c(title, xlab), ], size="last"))

enter image description here

(with obvious caveats)


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

...