Force X axis text on for all facets of a facet_grid plot

牧云@^-^@ 提交于 2019-11-26 16:15:41

问题


I have the same problem as this user: I'd like to make a facet_grid plot with a discrete x-axis, and I'd like to have the x-axis labels be written under each facet rather than only underneath the bottom row of facets. For instance:

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

However, I'd prefer not to use the solution from that post, which was just to use facet_wrap instead of facet_grid, because I prefer the way facet_grid labels the strip text with one variable on top of the columns, and the other variable on the sides of the rows.

Is there a way to get x-axis labels under each facet, when all the x-axes are actually the same, using facet_grid?


回答1:


You can insert a copy of the axes inside the 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)




回答2:


Script can be much simpler by using cbind.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:::cbind.gtable(
    g[seq.int(min(top)), ], 
    g[max(top)+1,],
    g[seq(min(top)+1, nrow(g)),], 
    size = "first")
grid.newpage()
grid.draw(all)


来源:https://stackoverflow.com/questions/17661052/force-x-axis-text-on-for-all-facets-of-a-facet-grid-plot

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