I have a grouped bar plot (two conditions with two groups in each). I am not having trouble creating the group bar plots, but I am interested in putting individual data points on the plot and connecting them with a line. More specifically, the lines should be connected within conditions, so the data point from condition 1 group 1 connects to the corresponding data point in condition 1 group 2. I cannot find a way to do this without using facet_wrap.
I have seen facet_wrap being suggested here, but it affects the alignment of the plots when using patchwork specifically. I have provided some code for the bar plots and the code to produce the facet_wrap plot.
I am open to any suggestions which do not use facet_wrap. I was hoping there would be a way to do it directly using geom_line(aes(subject))
, but that does not seem to be grouping correctly.
Code
df <- data.frame(
Subject = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3),
Condition = c(“A”, “A”, “B”, “B”, “A”, “A”, “B”, “B”, “A”, “A”, “B”, “B”),
Group = c(“group1”, “group2", “group1”, “group2",
“group1”, “group2", “group1”, “group2",
“group1”, “group2", “group1”, “group2"),
Value = c(10, 7, 8, 9, 11, 12, 13, 2, 2, 3, 4, 5))
Desired Look (excluding the connected data points)
ggplot(df, aes(x=Condition, y=Value, fill=Group)) +
stat_summary(fun.data = mean_sdl, geom = ‘bar’, position = ‘dodge’) +
stat_summary(fun.data = mean_se, geom = ‘errorbar’, width = 0.2,
position = position_dodge(width = 0.9)) +
theme_minimal()
Connected Data Points (using undesired facet)
ggplot(df, aes(x=Group, y=Value, fill=Group)) +
stat_summary(fun.data = mean_sdl, geom = ‘bar’, position = ‘dodge’) +
stat_summary(fun.data = mean_se, geom = ‘errorbar’, width = 0.2,
position = position_dodge(width = 0.9)) +
theme_minimal() +
geom_line(aes(group = Subject), alpha = 0.2, position = position_nudge(c(.14, -.14))) +
facet_wrap(~Condition)
Here is an example of how facet affects the alignment in patchwork (image on the right). Because it assumes there should be an axis title everything is misaligned.
Ryan Panela is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.