I was wondering if there might be a way to glue together p1
and p2
plots to as closely as possible get the appearance (e.g., a single xlab
and ylab
, vs
value printed in a gray strip
) of my Desired_plot
?
library(ggplot2)
dat1 = subset(mtcars, vs == 0)
dat2 = subset(mtcars, vs == 1)
p1 <- ggplot(dat1, aes(mpg,vs)) geom_point()
p2 <- ggplot(dat2, aes(mpg,vs)) geom_point()
Desired_plot <- ggplot(mtcars, aes(mpg,vs)) geom_point()
facet_wrap(~vs)
CodePudding user response:
To get the strips you either need to fit geoms or annotations to the plots. I think an easier way would be to make them as individual ggplots and stick them on top using patchwork:
library(patchwork)
p3 <- ggplot(mapping = aes(x = 1, y = 1))
theme_void()
theme(panel.background = element_rect(color = NA, fill = 'gray85'),
plot.margin = margin(6, 6, 0, 6))
p4 <- p3 geom_text(aes(label = 1))
p3 <- p3 geom_text(aes(label = 0))
p2 <- p2
theme(axis.ticks.y = element_blank(),
axis.text.y = element_blank(),
axis.title = element_blank(),
plot.margin = margin(0, 3, 6, 3))
p1 <- p1
theme(plot.margin = margin(0, 6, 6, 6),
axis.title.x = element_text(hjust = 1))
(p3 p4) / (p1 p2) plot_layout(heights = c(1, 15))
CodePudding user response:
This gets you pretty close. We could probably get right up to it if we take more margin padding out.
library(patchwork)
p1 (p2 scale_y_continuous(labels = NULL, name = NULL)
theme(axis.ticks.y = element_blank(),
plot.margin = unit(c(1,1,1,0), "line")))