Following is a sample of my data and the graph:
name <- c("PT02","PT02","PT02","PT02", "PT04","PT04","PT04","PT04", "PT05", "PT05","PT05", "PT05")
speed <- rep(c(145, 145, 145,150, 150, 150), 2)
position <- rep(c("Supine","Supine", "Up"), 4)
pct_change <- c( -32, -46, -72, -28, -60, -54, -24, -16, -36, -20, -15, -7)
df <- data.frame(name, speed, position, pct_change)
ggplot(df, aes(x=position, y = pct_change))+
geom_point(aes(col = name), alpha = 0.5)+
geom_line(aes(group=name))+
facet_wrap(vars(speed))
With above code, the line connects the points vertically. What I intend to achieve is for every name, a dot to connect between position (Supine and Up). So if I have multiples in Supine, rather than a vertical line, for each one to be connected for the same name in Up.
Example of what I want it to look like: (without the vertical lines)
I've tried geom_line and geom_path, and grouping by name, but I can't seem to get this to work. I read somewhere that group=1 helps, but couldn't get that to work either.
I create a pivoted copy of df and pass it to geom_segment
library(tidyverse)
df %>%
pivot_wider(names_from = position, values_from = pct_change, values_fn = list) %>%
unnest(Supine) %>%
unnest(Up) %>%
ggplot(aes(x = "Supine", y = Supine)) +
geom_point(data = df, aes(position, pct_change, col = name), alpha = 0.5) +
geom_segment(aes(xend = "Up", yend = Up)) +
facet_wrap(vars(speed))