【问题标题】:plot observed data and predict data by two models (lm and lme) in the same plot在同一图中绘制观察数据并通过两个模型(lm 和 lme)预测数据
【发布时间】:2020-08-16 07:56:13
【问题描述】:

如何在同一个图中绘制观察数据和不同模型(lm 和 lme)的结果? 我尝试了下面的代码,但它只适用于积分。我想添加不同颜色的内联模型预测的数据。

#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

例如,ggplot2 中有什么方法吗?

【问题讨论】:

    标签: ggplot2 plot lm lme4 mixed-models


    【解决方案1】:

    这是一个方法!我喜欢使用broombroom.mixed 来获得一个完整的标题,其中包含每个模型的预测值。

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      相关资源
      最近更新 更多