R. Saeiti
R. Saeiti

Reputation: 89

Plotting two longitudinal variables against time in r

Say I have a data that included two longitudinal variables (x1, x2), t is time (years), and type is class:

set.seed(20)
x1 = rnorm(20,5,1) 
x2 = (x1 + rnorm(20))
t = rep(c(0,1,2,3), 5)
id = rep(1:5,each = 4)
type = as.factor(c(rep(0,8), rep(1,12)))
df = data.frame(id, t, x1, x2, type)

Is it possible to plot x1 and x2 agnist t in one plot? Actually, I am trying to see the relationship between x1 and x1 (but here use rnorm to make it easy) by modified the correlation matrix.

Upvotes: 0

Views: 782

Answers (1)

user2133017
user2133017

Reputation: 91

Not sure how you want to treat the ID variable, but maybe try this?

require(reshape)
df <- reshape::melt(df, id.vars = c('id', 't', 'type'))
ggplot(df, aes(x = t, y = value, color = variable)) +
    geom_line() +
    facet_wrap(~id)

ggplot

Upvotes: 1

Related Questions