0

For this data:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50,1)
)

I would like to connect the pairwise observations in Q and Agrouped by ID. Here's what I have so far:

df %>%
  pivot_longer(-ID) %>% 
  ggplot(aes(x = factor(name), y = value, fill = factor(name)))+
  geom_jitter(width = 0.1, alpha = 0.5, col = "blue")+
  geom_line(aes(group = ID),
            alpha = 0.5)

enter image description here But there are two issues:

  • (i) I'm not sure the connecting lines are really between the observations with the same ID
  • (ii) the starting points and end points of the connecting lines are not jittered, therefore they do not always coincide with the dots.

How can these issue be dealt with?

Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • Chris, check the linked thread and a suggested different visualisation approach for this – tjebo Apr 04 '23 at 10:21

1 Answers1

2

To fix your issues set position_jitter explicitly for both the points and the lines so that both are jittered by the same amount and for the lines switch to geom_path:

library(tidyr)
library(ggplot2)

pj <- position_jitter(seed = 1, width = .1, height = 0)

df %>%
  pivot_longer(-ID) %>%
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +
  geom_point(
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  geom_path(aes(group = ID),
    alpha = 0.5,
    position = pj
  )

stefan
  • 90,330
  • 6
  • 25
  • 51