Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

enter image description here

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?

like image 285
Drew Steen Avatar asked Jul 15 '13 18:07

Drew Steen


2 Answers

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)

enter image description here

like image 86
baptiste Avatar answered Sep 22 '22 04:09

baptiste


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)
like image 30
Dongdong Kong Avatar answered Sep 20 '22 04:09

Dongdong Kong