A rough way to control facet_wrap layout by using a factor with added levels:
In response to: @coolbutuseless: Anyone know how to get multiple facet_wrap plots to have same layout?
library('ggplot2')
dfr <- mtcars
drop = FALSE
Add levels, to make up to a multiple of desired facet layout (ncol * nrow
):
dfr$cyl_f <- factor(dfr$cyl, levels = c(sort(unique(dfr$cyl)),'', ' ', ' '))
levels(dfr$cyl_f)
## [1] "4" "6" "8" "" " " " "
Use drop = FALSE
to ensure they’re plotted:
p <- ggplot(dfr, aes(am==1))
p <- p + geom_bar() +
facet_wrap(~cyl_f, ncol = 2, nrow = 3, drop = FALSE)
p + ggtitle(label = 'Add factor levels & drop = FALSE')
grid
to redraw after removing grobs
(panels, strips & axes)A neater solution requires grid
by Paul Murrell. See “the tricky part” with ggplotGrob
in this StackOverflow answer from Stibu: adding empty graphs to facet_wrap in ggplot2.
library('grid')
# library('gridExtra')
p <- p + geom_bar() +
facet_wrap(~cyl_f, ncol = 2, nrow = 3, drop = FALSE
# , scales = 'free_x' # could use to avoid hanging x-axis labels
) +
ggtitle(label = 'Remove Grobs for Panels, Strips & Axes')
g <- ggplotGrob(p)
names(g$grobs)
## [1] "" "panel1" "panel2" "panel3" "panel4" "panel5"
## [7] "panel6" "strip_t1" "strip_t2" "strip_t3" "strip_t4" "strip_t5"
## [13] "strip_t6" "axis_l1" "axis_l2" "axis_l3" "axis_l4" "axis_l5"
## [19] "axis_l6" "axis_b1" "axis_b2" "axis_b3" "axis_b4" "axis_b5"
## [25] "axis_b6" "" "" ""
g$layout$name
## [1] "background" "panel-1" "panel-2" "panel-3" "panel-4"
## [6] "panel-5" "panel-6" "strip_t-1" "strip_t-2" "strip_t-3"
## [11] "strip_t-4" "strip_t-5" "strip_t-6" "axis_l-1" "axis_l-2"
## [16] "axis_l-3" "axis_l-4" "axis_l-5" "axis_l-6" "axis_b-1"
## [21] "axis_b-2" "axis_b-3" "axis_b-4" "axis_b-5" "axis_b-6"
## [26] "xlab" "ylab" "title"
# remove panels, strips & axes,
# but keep x-axis labels from facets 5 & 6 (axis_b5 & axis_b6)
g$grobs[names(g$grobs) %in% c("panel4","panel5","panel6"
,"strip_t4","strip_t5","strip_t6"
,"axis_l4","axis_l5","axis_l6"
,"axis_b4"
# ,"axis_b5","axis_b6"
)] <- NULL
## remove them from the layout
g$layout <- g$layout[!(g$layout$name %in% c("panel-4","panel-5","panel-6"
,"strip_t-4","strip_t-5","strip_t-6"
,"axis_l-4","axis_l-5","axis_l-6"
,"axis_b-4"
# ,"axis_b-5","axis_b-6"
)),]
# grid.newpage()
grid.draw(g)