用ggplot中的线连接分组点

时间:2019-01-28 17:53:45

标签: r ggplot2

我有一个具有两个分类条件的数据集(条件A的级别为A1和A2,条件B的级别为B1和B2)。每个被测对象贡献四个数据点,两个条件的每个组合一个。

我已经绘制了各个数据点(添加了一些抖动),并希望将每个对象的两个点连接到A的每个级别(因此,将每个红色点与属于该对象中相同对象的相邻绿松石点连接起来)示例图)。我尝试使用geom_line(),但未指定线连接相同水平A的点。可能有一些使用facet_grid()而不是分组的解决方案,但是由于这只是更复杂图的一部分,我希望有一种可以保持分组的解决方案。

d <- data.frame(id=as.factor(rep(1:100, each=4)),
            A=rep(c("A1", "A1", "A2", "A2"), 100),
            B=rep(c("B1", "B2", "B1", "B2"), 100),
            y=runif(400))


ggplot(d, aes(x=A, y=y, col=B)) + geom_point(position=position_jitterdodge(.5)) 

enter image description here

1 个答案:

答案 0 :(得分:1)

(由@aosmith的answer here启发来类似的问题)

我建议在ggplot之前先抖动-这样点和线都可以使用相同的点。

library(dplyr)
d_jit <- d %>%
  # position on x axis is based on combination of B and jittered A. Mix to taste.
  mutate(A_jit = as.numeric(B)*0.5 - 0.75 + jitter(as.numeric(A), 0.5),
         grouping = interaction(id, A))

# Trick borrowed from https://stackoverflow.com/questions/44656299/ggplot-connecting-each-point-within-one-group-on-discrete-x-axis
# ... x-axis defined using A and geom_blank, but added layers use A_jit
ggplot(d_jit, aes(x=A,  y=y,  group = grouping)) + 
  geom_blank() +
  geom_line(aes(A_jit), alpha = 0.2) +
  geom_point(aes(A_jit, col=B))

enter image description here