Created
March 31, 2022 00:51
-
-
Save sdtaylor/e6d168b968da18031288f0232e42dae0 to your computer and use it in GitHub Desktop.
ggplot interaction plot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(tidyverse) | |
timing_results = tribble( | |
~treatment, ~object, ~mouse_id, ~time, | |
'vehicle', 'familiar', '1', 15, | |
'vehicle', 'novel', '1', 55, | |
'vehicle', 'familiar', '2', 19, | |
'vehicle', 'novel', '2', 60, | |
'vehicle', 'familiar', '3', 25, | |
'vehicle', 'novel', '3', 48, | |
'vehicle', 'familiar', '4', 22, | |
'vehicle', 'novel', '4', 59, | |
'THC', 'familiar', '5', 15, | |
'THC', 'novel', '5', 18, | |
'THC', 'familiar', '6', 19, | |
'THC', 'novel', '6', 20, | |
'THC', 'familiar', '7', 25, | |
'THC', 'novel', '7', 26, | |
'THC', 'familiar', '8', 22, | |
'THC', 'novel', '8', 25, | |
) | |
timing_results = timing_results %>% | |
mutate(x_offset = case_when( | |
object == 'familiar' ~ -0.25, | |
object == 'novel' ~ 0.25 | |
)) | |
#------------- | |
# Option #1, Use a nudge to adjust the x-axis the desired amount. | |
# position_nudge technically does not take a vector but this seems to work ok. | |
ggplot(timing_results, aes(x=treatment, y=time)) + | |
geom_line(aes(group=mouse_id), position = position_nudge(y=0, x=timing_results$x_offset)) + | |
geom_point(aes(color=object, shape=object), position = position_nudge(y=0, x=timing_results$x_offset), size=5) + | |
scale_color_manual(values=c('black','grey70')) + | |
scale_shape_manual(values=c(19,15)) + | |
theme_classic(15) | |
#------------- | |
# Option #2, make the x axis a continuous variable, with labels mapped | |
# to the treatment names via a factor. This avoids the potential nudge issue not taking vectors. | |
timing_results = timing_results %>% | |
mutate(treatment = as.factor(treatment)) | |
ggplot(timing_results, aes(x=as.numeric(treatment) + x_offset, y=time)) + | |
geom_line(aes(group=mouse_id)) + | |
geom_point(aes(color=object, shape=object), size=5) + | |
scale_x_continuous(breaks = c(1,2), labels=levels(timing_results$treatment)) + | |
scale_color_manual(values=c('black','grey70')) + | |
scale_shape_manual(values=c(19,15)) + | |
theme_classic(15) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment