gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:11:47 26 4
gpt4 key购买 nike

我使用 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

绘图

enter image description here

最佳答案

我编造了虚拟数据,因为出于某种原因,将您的 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 填充。因此,如果一个面板有两个模型,每个模型的 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())

enter image description here

如果我留下了重复项(此处为 -7,类型 1 为 -15,类型 2 为 -11),geom_text 将是杂乱无章的粗体模糊。重复的文本标签在 ggplot2 中呈现不佳。由于不可能真正按照您想要的方式进行,因此我们在这里只是为每个面板制作一个假比例。如果您不喜欢数字左侧的 y 轴上有一条额外的线,可以将其删除:

  ... + 
theme(panel.grid = element_blank(),
panel.border = element_blank(),
axis.line.x = element_line())

enter image description here

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com