1

I have a data set with two categorical conditions (condition A with levels A1 and A2, condition B with levels B1 and B2). Each measured subject contributes four data points, one for each combination of the two conditions.

I have plotted the individual data points (with some jitter added) and would like to connect the two points from each subject at each level of A (so connect each red point with the adjacent turquois point belonging to the same subject in the example plot). I've tried using geom_line(), but failed to specify that lines connect points of the same level of A. There might be some solutions using facet_grid() instead of the grouping but since this is only a part of a more complex plot, I would prefer having a solution that keeps the grouping.

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

Alain Merigot
  • 10,667
  • 3
  • 18
  • 31
mesolimbic
  • 23
  • 6

1 Answers1

5

(Inspired by @aosmith's answer here to a similar question)

I'd suggest jittering before ggplot -- that way both the points and the lines can use the same points.

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

Jon Spring
  • 55,165
  • 4
  • 35
  • 53