I was so happy to find most of the solution to my question in the message, " X Force Axis Text for all faces of the facet_grid plot " .
I would like to create a graph similar to the OP Drew Steen, except that I have more than two facet lines, and I would like to make the x-axis labels different for each row.
I made a super-hacker solution from @baptiste's amazing answer (mainly because I am not familiar with the gtable package) and I would like to know:
- If there is a more elegant solution than the mess I wrote below
- How to insert labels for the string "Premium" (middle).
Here is the code I adapted from @Drew Steen and @baptiste,
library(ggplot2)
diamondSub <-subset(diamonds, (cut=="Ideal" | cut=="Premium" | cut == "Very Good") & (color=="E" | color=="I"))
p<- ggplot(diamondSub, aes(x=carat, y=price)) +
geom_blank()+
geom_point() +
scale_x_discrete(breaks=c(1, 2, 3, 4), labels=c("a", "b", "c", "d")) +
facet_grid(cut~color, scales="free_x")
p
p2<- ggplot(diamondSub, aes(x=carat, y=price)) +
geom_blank()+
geom_point() +
scale_x_discrete(breaks=c(1, 2, 3, 4), labels=c("f", "g", "h", "i")) +
facet_grid(cut~color, scales="free_x")
p2
library(gtable)
g <- ggplotGrob(p)
g2 <- ggplotGrob(p2)
panels <- grep("panel", g$layout$name)
panels2 <- grep("panel", g2$layout$name)
top <- unique(g$layout$t[panels])
top2 <- unique(g2$layout$t[panels2])
all <- gtable:::rbind_gtable(gtable:::rbind_gtable(g[seq.int(min(top)), ],
g[max(top)+1,], "first"),
g2[seq(min(top2)+1, nrow(g2)),], "first")
grid.newpage()
grid.draw(all)
