我尝试在 x 轴上连接来自两种不同方法 (measure) 的测量值之间的抖动点。这些测量值通过先证者 (a) 相互关联,可以分为两个主要组,患者 (pat) 和对照 (ctr), 我的 df 是这样的:
set.seed(1)
df <- data.frame(a = rep(paste0("id", "_", 1:20), each = 2),
value = sample(1:10, 40, rep = TRUE),
measure = rep(c("a", "b"), 20), group = rep(c("pat", "ctr"), each = 2,10))
我试过了
library(ggplot2)
ggplot(df,aes(measure, value, fill = group)) +
geom_point(position = position_jitterdodge(jitter.width = 0.1, jitter.height = 0.1,
dodge.width = 0.75), shape = 1) +
geom_line(aes(group = a), position = position_dodge(0.75))
由 reprex package 创建于 2020-01-13 (v0.3.0)
我使用了 fill
美学来将抖动的点与两组(pat 和 ctr)分开。我意识到,当我将 group = a
美学放入 ggplot
主调用中时,它并没有很好地分离,但似乎更好地链接到要点。
我的问题:有没有办法更好地将线连接到(抖动的)点,但保持两个主要组 ctr 和 pat 的分离?
非常感谢。
最佳答案
你遇到的大问题是你只通过 group
来躲避点,但是 a
也躲过了线。
要使您的线与轴保持原样,一种选择是手动躲避您的数据。这利用了引擎盖下的整数因子,将 group
的一个级别向右移动,另一个向左移动。
df = transform(df, dmeasure = ifelse(group == "ctr",
as.numeric(measure) - .25,
as.numeric(measure) + .25 ) )
然后您可以用 measure
作为 x 轴绘制一个图,然后在 geom_point
和 geom_line< 中使用“dodged”变量作为 x 轴变量
.
ggplot(df, aes(x = measure, y = value) ) +
geom_blank() +
geom_point( aes(x = dmeasure), shape = 1 ) +
geom_line( aes(group = a, x = dmeasure) )
如果您还想要抖动,也可以手动将其添加到您的 x 和 y 变量中。
df = transform(df, dmeasure = ifelse(group == "ctr",
jitter(as.numeric(measure) - .25, .1),
jitter(as.numeric(measure) + .25, .1) ),
jvalue = jitter(value, amount = .1) )
ggplot(df, aes(x = measure, y = jvalue) ) +
geom_blank() +
geom_point( aes(x = dmeasure), shape = 1 ) +
geom_line( aes(group = a, x = dmeasure) )
关于r - 连接抖动点的线 - 多组躲避,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656299/