I have a facetted plot like this:
ggplot(mtcars, aes(x = hp, y = mpg))
geom_point()
facet_grid(. ~ carb)
The layout is currently like this : 1 2 3 4 6 8
Is it possible to set the layout of the facets, i.e. to set number of columns (or rows) like?
1 4 8
2 6
3
CodePudding user response:
One option to achieve your desired result would be to use ggh4x::facet_manual
which via the design
argument allows specify the layout of the facet panels:
library(ggplot2)
library(ggh4x)
design <- "
ADF
BE#
C##
"
ggplot(mtcars, aes(x = hp, y = mpg))
geom_point()
facet_manual(~ carb, design = design)
Instead of a character vector you could also set the order of the layout via a matrix
where an NA
creates a blank panel:
design <- matrix(c(1:3, 4:5, NA, 6, NA, NA), 3, 3)
ggplot(mtcars, aes(x = hp, y = mpg))
geom_point()
facet_manual(~ carb, design = design)
EDIT Not a perfect but a quick option to some kind of column titles would be to use patchwork
:
p1 <- ggplot(mtcars, aes(x = hp, y = mpg))
geom_point()
facet_manual(~ carb, design = design)
p2 <- ggplot(data.frame(x = c("gender","sex","age")))
facet_wrap(~x, strip.position = "bottom")
theme_void()
theme(strip.text.x = element_text(margin = margin(5.5, 5.5, 5.5, 5.5, "pt")))
library(patchwork)
p2 p1
plot_layout(heights = c(1, 100))