使用ggplot2翻转小平面标签和x轴

wes*_*oth 5 r ggplot2 facet-wrap axis-labels

我希望在1行和5列的刻面板上翻转标签,以便小平面标题显示在底部,x轴显示在小平面的顶部.

原因是我想重新使用那些将直接位于图表下方的表格.

所以在这个例子中......

library(ggplot2)

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

my.hist + facet_wrap( ~ cut, ncol=5) + coord_flip()
Run Code Online (Sandbox Code Playgroud)

我希望"剪切"标签显示在图表下方.我以为facet_grid可能会持有密钥,但这只是猜测.

有谁知道怎么做到这一点?

bap*_*ste 7

获得小图下方的小平面条很容易,

library(gtable)
g <- ggplotGrob(p)

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

但是,轴需要更加小心,因为必须反转刻度线和标签的位置.你可以从这开始,

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)
Run Code Online (Sandbox Code Playgroud)

编辑:根据上述内容,可能会出现"完整"的解决方案

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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

(有明显的警告)