Reputation: 1295
I have panel data that that I want to visualize using ggplot2
such that each individual gets its own line and its color reflects the group that it is apart of. For example:
require(ggplot2)
set.seed(123)
frame <- data.frame(id = 1:6, month1 = sample(0:1, 6, replace = TRUE), month2 = sample(0:1, 6, replace = TRUE), month3 = sample(0:1, 6, replace = TRUE), group1 = rep(0:1, 3), group2 = rep(1:0, 3))
frame2 <- reshape(data = frame, direction = "long", idvar = "id", timevar = "time", varying = list(2:4))
ggplot(frame2, aes(x = time, y = month1, group = id, colour = id)) + geom_smooth()
In this plot, I would like each member of group1 to be red and each member of gruop2 to be blue and have each individual get its own line. Any idea on how to do this? Thanks.
Upvotes: 1
Views: 58
Reputation: 5089
You were close. You might consider jittering the lines as well if in your real application the Y axis variable is discrete.
ggplot(frame2, aes(x = time, y = month1, group = as.factor(id),
colour = as.factor(group2))) + geom_smooth()
Upvotes: 1