1

How can I plot observed data and the results of differents models (lm and lme) in the same plot? I tried the code below, but it only worked for points. I would like to add the data predicted by the inline models of different colors.

#Data
d <- runif(160,0,100)#data
y <- rnorm(16,1,0.05)*x + rnorm(16,0,0.5)#data
df = data.frame(d,y)

#Models
#linear - 1
m1 = lm(y~d, data = df)
summary(m1)
# linear - 2
m2 = lm(y~d+I(d^2), data = df)
summary(m2)

df$Class10<-with(df,ifelse(d<20,"<20",ifelse(d<30,"20-30",
 ifelse(d<40,"30-40",ifelse(d<50,"40-50",ifelse(d<60,"50-60",
 ifelse(d<70,"60-70",ifelse(d<80,"70-80",ifelse(d<90,"80-90",
 ifelse(d>=90,">90","ERROR"))))))))))
# number of classes
length(unique(df$Class10))
# classes
sort(unique(df$Class10))
# observations by class
table(df$Class10)
plot(table(df$Class10))

# b0
m10 = lme(y~d, random=~1|Class10, method="ML" ,data = df)

# b1
m10 = lme(y~d, random=~-1+d|Class10, method="ML" , data = df)

# 
m10 = lme(y~d, random=~d|Class10, method="ML" , data = df,
control = lmeControl(niterEM = 5200, msMaxIter = 5200))

#plot points - It works
plot(df$d, df$y)  
points(df$d, predict(m1), col="blue")
points(df$d, predict(m10, level=1), col="red")

#curve
plot(df$d, df$y)
curve(predict(m1,newdata=data.frame(d=x)),lwd=2, add=T)
curve(predict(m10,newdata=data.frame(d=x)),lwd=1, add=T)#error
# line
plot(df$d,df$y)  
curve(predict(m1,newdata=data.frame(d=x)),lwd=2, add=T)
lines(df$d, predict(m10, level=1),col="green")#error

Is there any way in ggplot2, for example?

1 Answer 1

1

Here is a way! I like using broom and broom.mixed to get a complete tibble with predicted values for each model.

library(tidyverse)
library(lme4)
library(broom)
library(broom.mixed)


df <- ChickWeight

lin <- lm(weight ~ Time,df)

mlm <- lmer(weight ~ Time + (1 | Chick),df)

df <- df %>% 
  mutate(linpred = broom::augment(lin)[,3] %>% pull(),
         mlmpred = broom.mixed::augment(mlm)[,4] %>% pull())

ggplot(df,aes(Time,weight,group = Chick)) + 
  geom_line(alpha = .2) + 
  geom_line(aes(y = linpred,color = 'Fixed Linear Effect')) + 
  geom_line(aes(y = mlmpred,color = 'Random Intercepts'), alpha = .4) +
  scale_color_manual(values = c('blue','red')) +
  labs(color = '') +
  theme_minimal()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.