我想基于id
连接图中的点。问题是在x轴上我将geom_point()
与position_dodge()
定位在一起,所以我不确定如何映射它。
代表:
library(ggplot2)
df <- structure(list(id = c("id24", "id24", "id27", "id27", "id29",
"id29", "id34", "id34", "id35", "id35", "id44", "id44", "id01",
"id01", "id03", "id03", "id04", "id04"), phase = c("time1", "time2",
"time1", "time2", "time1", "time2", "time1", "time2", "time1",
"time2", "time1", "time2", "time1", "time2", "time1", "time2",
"time1", "time2"), value = c(3.72638957446809, 3.92324338297872,
3.7271745106383, 3.79455578723404, 3.96383646808511, 4.28965153829787,
4.44174112765957, 4.80494985106383, 4.11124778723404, 4.39377629787234,
2.91550910638298, 3.21677434042553, 3.4524314893617, 4.2533229787234,
3.07149085106383, 3.38445914893617, 3.8882985106383, 4.78346468085106
), group = c("group1", "group1", "group1", "group1", "group1",
"group1", "group2", "group2", "group2", "group2", "group2", "group2",
"group3", "group3", "group3", "group3", "group3", "group3")), row.names = c(NA,
-18L), class = c("tbl_df", "tbl", "data.frame"))
ggplot(df, aes(group, value)) +
geom_point(aes(group = phase), position = position_dodge(width = 0.5)) +
theme_light()
由reprex package(v0.3.0)于2020-07-08创建
我知道这将是最简单的方法:
ggplot(df, aes(phase, value)) +
geom_point(position = position_dodge(width = 0.5)) +
geom_line(aes(group = id)) +
theme_light()
由reprex package(v0.3.0)于2020-07-08创建
但是我需要在x轴上放置group
,然后再通过phase
对其进行定位。有什么想法吗?
答案 0 :(得分:3)
听起来您正在寻找的实际上是嵌套的分类x轴。这是ggplot中的功能,但并不是您想要的外观。但是,您可以设置各种主题元素以隐藏您所面临的事实。我认为这比替代方法要容易得多,后者是将数据放在phase
上并为每个geom_segment
绘制id
,但是这也需要对x轴分类进行一些欺骗,并给出基本相同的结果:
ggplot(df, aes(phase, value)) +
geom_point(aes(color = id)) +
geom_vline(aes(xintercept = c(1.5)), colour = "gray85") +
geom_vline(aes(xintercept = c(0.5)), colour = "gray85") +
geom_line(aes(group = id, color = id)) +
coord_cartesian(xlim = c(0.5, 2.5), ylim = c(2.49, 5), expand = 0) +
theme_light() +
labs(x = "group") +
facet_wrap(.~group, strip.position = "bottom") +
theme(strip.placement = "outside",
axis.text.x = element_blank(),
strip.text.x = element_text(colour = "black"),
strip.background = element_rect(fill = "white"),
panel.spacing.x = unit(0, "npc"),
panel.border = element_rect(fill = NA, colour = NA),
panel.grid.major.x = element_blank())
不分面:
df %>%
pivot_wider(names_from = "phase") %>%
mutate(group = as.factor(group)) %>%
mutate(x0 = as.numeric(group) - 0.25, xend = as.numeric(group) + 0.25) %>%
ggplot(aes(x = group, colour = id)) +
geom_point(aes(x = x0, y = time1)) +
geom_point(aes(x = xend, y = time2)) +
geom_segment(aes(x = x0, y = time1, xend = xend, yend = time2)) +
scale_x_continuous(breaks = 1:3, labels = levels(as.factor(df$group))) +
theme_light()