Flip facet label and x axis with ggplot2

。_饼干妹妹 提交于 2019-11-28 11:29:45

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"))

(with obvious caveats)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!