我正在使用facet_wrap 创建一个 2x2 ggplot,其中列是两个不同的组。 这意味着列上的 x 轴在顶行和底行之间是相同的,但在列之间是不同的。我想在重复时删除重复的 x 轴刻度标签。
facet_wrap 中的列之间的 x 轴是否可以变化?
这是数据的玩具示例,也是我迄今为止所尝试的。当我使用参数“scales = free_x”时,您将看到 x 轴在顶行和底行重复。如果我不使用 free_x,那么 x 轴的比例对于每个图来说都太宽。
有一个我可以使用的论点,或者我应该考虑像拼凑一样的东西来将图连接在一起?
library(ggplot2)
n = 100
df = data.frame(x = c(rnorm(n/2), rnorm(n/2, mean = 100)),
y = rnorm(n),
group = rep(1:2, each = n/2),
facet = rep(c("A", "C", "B", "D"), each = n/4))
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~facet + group, scales = "free_x")
根据您想要的结果
patchwork
将为您提供最大的灵活性。至少让您接近所需结果的第二个选项是使用 ggh4x::facetted_pos_scales
,它允许为每个面板单独设置比例。但是,我只找到了一个选项来删除顶行的轴标签,但没有删除刻度线。
library(ggplot2)
set.seed(123)
n <- 100
df <- data.frame(
x = c(rnorm(n / 2), rnorm(n / 2, mean = 100)),
y = rnorm(n),
group = rep(1:2, each = n / 2),
facet = rep(c("A", "C", "B", "D"), each = n / 4)
)
scale_y <- df |>
split(~ group + facet, drop = TRUE) |>
lapply(
\(x) {
labels <- if (!unique(x$facet) %in% c("A", "B")) waiver()
limits <- range(df[df$group == unique(x$group), "x"])
scale_x_continuous(
labels = labels,
limits = limits
)
}
)
ggplot(data = df, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~ facet + group,
scales = "free_x"
) +
ggh4x::facetted_pos_scales(
x = scale_y
)
这是另一种方法,它依赖于为每个
facet + group
添加虚拟点,其所需的x
范围和y
值大于整个数据的最大值,但将它们取出(不在绘图上显示它们)通过定义所需的 ylim
。
n = 100
set.seed(123)
df = data.frame(x = c(rnorm(n/2), rnorm(n/2, mean = 100)),
y = rnorm(n),
group = rep(1:2, each = n/2),
facet = rep(c("A", "C", "B", "D"), each = n/4))
library(ggplot2)
library(dplyr)
df %>%
bind_rows(
reframe(df, x = c(min(x), max(x)), y = max(df$y) + 10,
facet = unique(facet),
.by = group),
reframe(df, x = c(min(x), max(x)), y = max(df$y) + 10,
facet = rev(unique(facet)),
.by = group)) %>%
ggplot(aes(x = x, y = y)) +
geom_point() +
facet_wrap(~ facet + group, scales = "free_x") +
coord_cartesian(ylim = range(df$y))
创建于 2024-03-22,使用 reprex v2.0.2