Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...