This is an example of my data and the graph I'm trying to make
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))
When I do this, however, the line connects the points vertically, but what I want 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 would be grateful for any ideas.
CodePudding user response:
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))