这里是带有facets的ggplot示例代码。
当前代码创建了一个
2 by 4
绘图面板。我最重要的分类变量是 A。我想根据 A 的值明确分离图,即基于 A 的值的 2 组/嵌套 2 by 2
面板。
谢谢
library(tidyverse)
# continuous variables
x <- runif(160)
y <- runif(160)
# 3 categorical variables, each with 2 levels
A <- c(rep(0, 80), rep(1, 80))
b <- c(rep(0, 40), rep(1, 40), rep(0, 40), rep(1, 40))
c <- c(rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20),
rep(0, 20), rep(1, 20), rep(0, 20), rep(1, 20))
# tibble
tbl <- tibble(x, y, A, b, c) %>%
# rename the categorical variables for better labels in facet panels
mutate(A = factor(A, levels = c(1, 0), labels = paste0("A = ", c(1, 0)))) %>%
mutate(b = factor(b, levels = c(1, 0), labels = paste0("b = ", c(1, 0)))) %>%
mutate(c = factor(c, levels = c(1, 0), labels = paste0("c = ", c(1, 0))))
# ggplot
ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_point() +
facet_grid(c ~ A + b) +
theme_bw() +
theme(aspect.ratio = 1)
[![在此处输入图像描述][1]][1]
由于编辑 grobs 对于新手来说有点棘手,因此您可以通过以下方式实现Allan Cameron在这个答案中提供的出色解决方案。
首先,将绘图保存到变量中。
p <- ggplot(data = tbl,
aes(x = x,
y = y)) +
geom_point() +
facet_grid(c ~ A + b) +
theme_bw() +
theme(aspect.ratio = 1)
p
grob
并识别条带的位置。
library(tidyverse)
library(gtable)
library(grid)
g <- ggplot_gtable(ggplot_build(p))
stript <- grep("strip", g$layout$name)
然后使用Allan的代码,我稍微修改了
labs
中的变量和高度,但除此之外,他的代码是完全可重用的。
grid_cols <- sort(unique(g$layout[stript,]$l))
t_vals <- rep(sort(unique(g$layout[stript,]$t)), each = length(grid_cols)/2)
l_vals <- rep(grid_cols[seq_along(grid_cols) %% 2 == 1], length = length(t_vals))
r_vals <- rep(grid_cols[seq_along(grid_cols) %% 2 == 0], length = length(t_vals))
labs <- levels(as.factor(p$data$A))
for(i in seq_along(labs))
{
filler <- rectGrob(y = 0.72, height = 0.57, gp = gpar(fill = "gray85", col = "black"))
tg <- textGrob(label = labs[i], y = 0.75, gp = gpar(cex = 0.8))
g <- gtable_add_grob(g, filler, t = t_vals[i], l = l_vals[i], r = r_vals[i],
name = paste0("filler", i))
g <- gtable_add_grob(g, tg, t = t_vals[i], l = l_vals[i], r = r_vals[i],
name = paste0("textlab", i))
}
grid.newpage()
grid.draw(g)
这对你有用吗:
library(patchwork)
P1 <- tbl %>% filter (A == "A = 1") %>%
ggplot(aes(x = x,
y = y)) +
geom_point() +
facet_grid(c ~ b) +
theme_bw() +
theme(aspect.ratio = 1)
P2 <- tbl %>% filter (A == "A = 0") %>%
ggplot(aes(x = x,
y = y)) +
geom_point() +
facet_grid(c ~ b) +
theme_bw() +
theme(aspect.ratio = 1)
P1 + P2
由 reprex 包于 2021-01-04 创建(v0.3.0)