我使用 geom_segment() 将 y 轴点映射到 x 轴,然后使用 facet_wrap 将数据分成两个图;然而,y 轴点出现在两个图上。

我怎样才能只有与每个 facet_wrap 相关的必要 y 轴点?

示例代码

dat <- structure(list(temp = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3,
4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5), rev = c(-5,
-11, -20, -29, -40, -9, -20, -32, -45, -57, -12, -24, -37, -50,
-62, -7, -20, -36, -52, -67, -5, -13, -23, -35, -47, -12, -24,
-36, -48, -58), type = c("Type 1", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1", "Type 1",
"Type 1", "Type 1", "Type 1", "Type 1", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2", "Type 2",
"Type 2", "Type 2", "Type 2", "Type 2", "Type 2"), model = c("A",
"A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "C",
"C", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C",
"C", "C", "C")), .Names = c("temp", "rev", "type", "model"), row.names = c(NA,
-30L), class = "data.frame")

p1 <- ggplot(dat, aes(temp, rev, color = model)) +
  geom_line() + geom_point() + geom_segment(aes(x = 0, xend = temp, yend = rev), linetype = "dashed", color = "grey") +
  facet_wrap(~type, scales = "free") + scale_y_continuous(breaks = dat$rev)
p1

绘制

使用 facet_wrap 和 geom_segment 删除不必要的 y 轴点-LMLPHP

最佳答案

我编造了虚拟数据,因为出于某种原因将您的 dput 粘贴到我的控制台中使其不高兴。

library(dplyr)

df <- expand.grid(temp = 1:5, model = LETTERS[1:3], type = 1:2) %>%
  group_by(model, type) %>%
  mutate(rev = -sort(sample.int(20, length(temp))))

# this is equivalent to your data as-is, structurewise
df.labeled <- df %>%
  ungroup() %>% group_by(type, rev) %>%
  mutate(label = c(rev[1], rep(NA, length(rev) - 1)))

在这里,我为每个组面板中显示的每个 y 值创建了一个组。然后我创建了一个 label 列,它包含对该 y 值的 1 个观察值,并用 NA s 填充。因此,如果面板有两个模型,每个模型都有 rev-5 ,那么现在它将是 -5, NA 而不是 -5, -5 。为什么我这样做会在下面变得更清楚。
ggplot(df.labeled, aes(temp, rev, color = model)) +
  geom_segment(aes(xend = 0, yend = rev), linetype = "dashed", color = "grey") +
  geom_text(aes(label = label, x = -0.1), colour = "black", hjust = 1) +
  geom_vline(xintercept = 0) +
  geom_point() + geom_line() + facet_grid(~type) +
  scale_y_continuous(breaks = NULL) +
  scale_x_continuous(limits = c(-0.5, NA)) +
  theme_bw() + theme(panel.grid = element_blank())

使用 facet_wrap 和 geom_segment 删除不必要的 y 轴点-LMLPHP

如果我保留了重复项(此处为 -7,类型 1 为 -15,类型 2 为 -11),那么 geom_text 将是一个凌乱的粗体模糊。重复的文本标签在 ggplot2 中不能很好地呈现。由于实际上不可能按照您想要的方式进行操作,因此我们只是为每个面板制作了一个假比例。如果您不喜欢数字左侧的 y 轴上有一条额外的线,可以去掉:
  ... +
  theme(panel.grid = element_blank(),
        panel.border = element_blank(),
        axis.line.x = element_line())

使用 facet_wrap 和 geom_segment 删除不必要的 y 轴点-LMLPHP

关于使用 facet_wrap 和 geom_segment 删除不必要的 y 轴点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45778044/

10-12 07:03