Reputation: 8880
I am making a ggplot
where I use facet_wrap
with two variables, say first var_1
with values A/B, second var_2
with 1/2, resulting into four facets, A-1, A-2, B-1, B-2. I would want the var_1
A/B title to show on top, and the var_2
1/2 to show up on the side.
Doing this with facet_wrap(~dim_1 +dim_2, ncol=1)
, it seems however the argument strip.position
will apply the same position for both? Another approach could be to use facet_grid()
(which does want I want, to have facets both horizontal and vertical) but does not allow to set the number of rows/columns!?
Code below, with actual output, and what I want to have!
library(ggplot2)
df <- data.frame(dim_1 = rep(c("A", "B"), each=4),
dim_2 = rep(c("1", "2"), times=4),
x = rnorm(8), y = rnorm(8))
p <- ggplot(aes(x=x, y=y), data=df) +
geom_point()
p+
facet_wrap(~dim_1 +dim_2, ncol=1, strip.position = c("left"))
Created on 2019-09-29 by the reprex package (v0.3.0)
Upvotes: 2
Views: 1427
Reputation: 66490
I don't know a way to accomplish that within ggplot itself, but another approach would be to combine two plots using patchwork
:
library(patchwork)
myplot <- function(section = "A") {
ggplot(subset(df, df$dim_1 == section), aes(x,y)) +
geom_point() +
# coord_cartesian(xlim = c(min(df$x), max(df$x))) + # To get single x scale between all plots
facet_grid(dim_2~dim_1, switch = "y")
}
myplot("A") / myplot("B")
Upvotes: 4