按ggplot中具有躲避位置的因子进行分组

slh*_*hck 3 r ggplot2

我们来看一些虚拟数据.我有各种科目,治疗和试验组合.事实上,每个受试者只与特定治疗配对(听起来很愚蠢,但这只是一个例子).

library(ggplot2)
d = read.table(text = '
subject   treatment trial     value
1    1    1    4.5
2    2    1    3.2
3    3    1    1.2
1    1    2    4.8
2    2    2    3.5
3    3    2    1.3
1    1    3    4.2
2    2    3    2.9
3    3    3    1
4    1    1    4.3
5    2    1    3.9
6    3    1    1.1
4    1    2    4.3
5    2    2    3.1
6    3    2    1.8
4    1    3    4
5    2    3    2.6
6    3    3    1.3
', header = TRUE)
d$treatment = as.factor(d$treatment)
d$subject = as.factor(d$subject)
d$trial = as.factor(d$trial)

dodge = position_dodge(.3)
p = ggplot(d, aes(x = treatment, y = value, color = trial, label = subject)) + 
  geom_point(position = dodge) +
  scale_y_continuous(breaks = pretty_breaks(n = 10)) +
  ylim(1,5) +
  geom_text(hjust = 1.5, position = dodge, size = 3)

print(p)
Run Code Online (Sandbox Code Playgroud)

我得到的情节是这样的:

我想在相同主题之间添加一条线,这意味着我想将左上角的所有"4"与黑线组合在一起.

一个简单的

geom_line(aes(group = subject), position = dodge)
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用,因为它在某种程度上不尊重位置而只是绘制一条垂直线:

我怎么能做到这一点?

had*_*ley 5

我认为你需要重新考虑你的方法 - 躲避不适用于线条.为什么不使用facetting并在x轴上明确显示试验?

ggplot(d, aes(trial, y = value)) + 
  geom_line(aes(group = subject)) +
  geom_point(aes(colour = treatment)) +
  geom_text(aes(label = subject), hjust = 1.5, size = 3)  +
  facet_wrap(~ treatment)
Run Code Online (Sandbox Code Playgroud)

.....