2013-07-15 37 views
16

我有和this user相同的问题:我想绘制一个具有离散x轴的facet_grid绘图,并且我想让x轴标签应写在每个面的下面,而不是只写在底面的一行面之下。例如:为facet_grid绘图的所有刻面强制X轴文本

# Drop some factor levels to make the plot smaller 
diamondSub <- subset(diamonds, (cut=="Ideal" | cut=="Premium") & 
        (color=="E" | color=="I")) 

# Note that scales="free_x" has no practical effect here 
ggplot(diamondSub, aes(x=clarity, y=price)) + 
    geom_blank()+ 
    geom_boxplot() + 
    facet_grid(cut~color, scales="free_x") 

enter image description here

不过,我宁愿不使用来自该职位,这是该解决方案只使用facet_wrap代替facet_grid,因为我喜欢的方式facet_grid标签条的文本在列的顶部有一个变量,而在行的两侧有另一个变量。

有没有办法让每个面在x轴标签,当所有的X轴实际上是相同的,使用facet_grid

回答

15

您可以将gtable内轴的副本,

library(gtable) 
g <- ggplotGrob(p) 
# locate the panels 
panels <- grep("panel", g$layout$name) 
top <- unique(g$layout$t[panels]) 
# intersperse a copy of the bottom axes 
all <- gtable:::rbind_gtable(gtable:::rbind_gtable(g[seq.int(min(top)), ], 
                g[max(top)+1,], "first"), 
          g[seq(min(top)+1, nrow(g)),], "first") 
grid.newpage() 
grid.draw(all) 

enter image description here

+0

我得到错误运行线'所有<一段时间 - gtable ::: rbind_gtable(gtable ::: rbind_gtable( g [1:4],g [7,]),g [5:9,])''。我得到的误差是'错误UseMethod(“grid.draw”): 施加到的类“功能”'的对象关于“grid.draw”不适用方法。我相信'p'指的是ggplot对象,这是真的吗? –

+0

是的,p是你的ggplot。你用'print(all)'得到了什么?它应该是一个'TableGrob(10×8) “布局”:16 grobs'等 – baptiste

+0

我现在得到的错误是如下:'>所有< -​​ gtable ::: rbind_gtable(gtable ::: rbind_gtable(克[1 :4],G [7,]),G [5:7,]) 错误MMM <每个:这些类型的比较是不implemented' –