How to align geom_line and geom_point when points are dodged by a variable and lines by another?

Viewed 188

Sample dataset:

df <- structure(list(event = c("Alpha", "Alpha", "Alpha", "Alpha", 
"Alpha", "Alpha", "Alpha", "Alpha", "Beta", "Beta", "Beta", "Beta", 
"Beta", "Beta", "Beta", "Beta"), ID = c("AV", "AV", "AV", "AV", 
"BD", "BD", "BD", "BD", "PH", "PH", "PH", "PH", "TC", "TC", "TC", 
"TC"), Split_Q = c("Q1", "Q2", "Q3", "Q4", "Q1", "Q2", "Q3", 
"Q4", "Q1", "Q2", "Q3", "Q4", "Q1", "Q2", "Q3", "Q4"), Time = c(82.2, 
87, 87.1, 87.2, 85.8, 86.6, 86.8, 86, 91.2, 92.2, 92.7, 90.4, 
92.7, 92.9, 92.6, 91.8)), row.names = c(NA, 16L), class = "data.frame")

I have two groups Alpha and Beta, which have an indeterminate amount of observations in my full dataset over four measurements (Q1-Q4). I want to clearly delineate the groups on each side of the four measurements:

plot <- df %>% ggplot(aes(Split_Q, Time, colour = event)) + 
  geom_point(position = position_dodge(0.5)) 

enter image description here

Looks okay so far, but when I add a geom_line with the ID variable identifying each observation, and the same position_dodge value, they don't align.

plot + geom_line(aes(group = ID), position = position_dodge(0.5))

enter image description here

Not sure what the procedure is to align them, any advice? Thanks

1 Answers

First add a bit of offset:

library(tidyverse)

df <- df %>% 
  mutate(Quarter = as.numeric(str_extract(Split_Q, "[:digit:]")),
         Quarter = case_when(event == "Alpha" ~ Quarter - 0.1,
                             event == "Beta" ~ Quarter + 0.1))

Plot and specify labels:

df %>% ggplot(aes(
    x = Quarter,
    y = Time,
    colour = event
  )) +
  geom_point() +
  geom_line(aes(group = ID)) +
  scale_x_continuous(labels = unique(df$Split_Q))

enter image description here

Related