Created
May 20, 2015 21:37
-
-
Save ahebrank/85ce24caaf0d82119679 to your computer and use it in GitHub Desktop.
spaghetti plots
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
# construct spaghetti plots in R | |
# skip to the last few lines for the actual ggplot definition | |
# | |
# melt to long format | |
# in this case, we have subjects with a dv collected | |
# 1) at multiple timepoints (wave) | |
# 2) in multiple brain regions (region) | |
# subjects also have an age, which helps make a prettier spaghetti plot | |
require(reshape2) | |
long_data <- melt(wide_data, id.vars=c("ID", "wave", "age")) | |
names(long_data) <- c("ID", "wave", "age", "region", "dv") | |
long_data$ID <- factor(long_data$ID) | |
# long_data should at this point have (subjects * waves * regions) rows | |
# calcuate the delta for each person | |
# this is only used to colorize the segments (i.e., use color to show slope) | |
# so skip if you don't need it | |
# recast back to wide, by waves | |
wide_data_delta <- dcast(long_data, ID+region~wave, value.var="dv") | |
wide_data_delta$delta <- wide_data_delta[["2"]] - wide_data_delta[["1"]] | |
long_data <- merge(long_data, subset(wide_data_delta, select=c("ID", "region", "delta")), by=c("ID", "region")) | |
# plot | |
require(ggplot2) | |
q <- ggplot(long_data, aes(x=age, y=dv, group=ID, colour=delta)) + | |
geom_line() + | |
geom_point() + | |
facet_wrap(~region) + theme_bw() + scale_colour_gradient2(low="green", high="red", mid="darkblue") | |
print(q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment