Any way to customize facet position?
thiagoveloso opened this issue · 2 comments
I am plotting a ggplot2
graph that has an uneven number of facets. My plot currently looks like this:
library(ggplot2)
df <- data.frame(group=c(1,1,2,2,3),
name=c('a','b','c','d','e'),
x=c(1,2,3,4,5),
y=c(2,3,4,5,6))
ggplot(df, aes(x,y)) + geom_point() + facet_wrap(~ name, ncol=3)
Note that the default positioning for the facets is:
a b c
d e
However, I would like to have a finer control on the positioning of the facets. Specifically, I would like to "center" the bottom two facets in order to distribute the void space more evenly on the sides of the plot.
In other words, the ideal placement for me would look like:
a b c
d e
Is this something I can achieve with cowplot
? How?
This is probably not the right place to ask these type of questions (you'd better try stackoverflow). Regardless, you could try something along the lines of:
library(tidyverse)
df <- data.frame(group=c(1,1,2,2,3),
name=c('a','b','c','d','e'),
x=c(1,2,3,4,5),
y=c(2,3,4,5,6))
top <- df %>%
filter(grepl("a|b|c", name)) %>%
ggplot(aes(x,y)) + geom_point() + facet_wrap(~ name, ncol=3)
bottom <- df %>%
filter(grepl("d|e", name)) %>%
ggplot(aes(x,y)) + geom_point() + facet_wrap(~ name, ncol=2)
cowplot::plot_grid(top,
cowplot::plot_grid(NULL, bottom, NULL, nrow=1, rel_widths = c(0.13, 0.73, 0.14)), nrow=2)
Basically, this code creates top and bottom facetted rows, then adds 2 empty plots at each side of the bottom row (last line), after which specific widths are given. You should play around with the widths to get this exactly right I presume.
The code above gives me:
Which seems about right. Use options in ggplot2 to drop any elements you do not need/set x-axis limits.
Awesome, it works! Thanks a lot @wsteenhu