Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force facet_wrap to fill bottom row (and leave any "gaps" in the top row)

Tags:

r

ggplot2

I'd like to force facet_wrap to fill from the top-left, but in such a way as to always fully fill the bottom row. (That is, from the top-left plus whatever horizontal offset is required to fully fill the bottom row.)

library(ggplot2)

n <- 1000
df <- data.frame(x=runif(n), y=rnorm(n), label=sample(letters[1:7], size=n, replace=TRUE))
df$label.rev <- factor(df$label, levels=sort(unique(df$label), decreasing=TRUE))

p <- ggplot(df, aes(x=x, y=y)) + geom_point()
p1 <- p + facet_wrap(~ label, ncol=3)
p2 <- p + facet_wrap(~ label, ncol=3, as.table=FALSE)
p3 <- p + facet_wrap(~ label.rev, ncol=3, as.table=FALSE)

p1: I'm happy with the left-to-right, top-to-bottom ordering of the labels, but I'd like the gap to be at the top left instead of the bottom right.

p2: Gap is now in the top row (top right rather than top left, unfortunately), but the label order is wrong.

p3: Similar to p2; attempts to fix the label order, and fails.

I'd like the facets to be ordered like this:

_ _ A
B C D
E F G

...so that there are axes along the entire bottom row, and because I think it would look better than the default. How can I do this?

like image 403
Adrian Avatar asked Aug 20 '13 14:08

Adrian


1 Answers

Would this fix suffice?

library(ggplot2)
n <- 1000
df <- data.frame(x = runif(n), y=rnorm(n), label = sample(letters[1:7], 
                 size = n, replace = TRUE), stringsAsFactors=TRUE)
# following @Didzis' suggestion (with some minor changes)
df$label.new <- factor(df$label, levels=sort(c(""," ",levels(df$label))))
p <- ggplot(df, aes(x=x, y=y)) + geom_point() + 
         facet_wrap(~ label.new, ncol=3,drop=FALSE)

enter image description here


EDIT (from @baptiste):

Starting from the last solution, it's easier to remove the grobs from the gtable,

g = ggplotGrob(p)
## remove empty panels
g$grobs[names(g$grobs) %in% c("panel1", "panel2", "strip_t.1", "strip_t.2")] = NULL
## remove them from the layout
g$layout = g$layout[!(g$layout$name %in% c("panel-1", "panel-2", 
                                                "strip_t-1", "strip_t-2")),]
## move axis closer to panel
g$layout[g$layout$name == "axis_l-1", c("l", "r")] = c(9,9)
grid.newpage()
grid.draw(g)

enter image description here

like image 195
Arun Avatar answered Oct 04 '22 19:10

Arun