混合模型/ lsmeans结果的线图(使用ggplot?)

时间:2017-04-13 13:53:59

标签: r plot ggplot2 mixed-models lsmeans

我对4个时间点的个体进行了纵向重复测量。在使用时间作为固定效应和随机斜率的混合模型分析之后,我使用lsmeans来估计每个时间点的平均值以及95%置信区间。我现在想绘制一个带有时间点(x)的线图和我的结果变量(y)与CI的平均值。我可以使用例如ggplot绘制我从lsmeans得到的结果?还是有另一种聪明的方式来绘制这个吗?

我从lsmeans得到的结果,以及我想绘制(lsmean,lower.CL,upperCL随时间变化)的结果是:

$lsmeans
time    lsmean        SE df  lower.CL upper.CL
0    21.967213 0.5374422 60 20.892169 23.04226
1    16.069586 0.8392904 60 14.390755 17.74842
2    13.486802 0.8335159 60 11.819522 15.15408
3     9.495137 0.9854642 60  7.523915 11.46636

Confidence level used: 0.95 

2 个答案:

答案 0 :(得分:2)

这是你的意思吗?

# To convert from lsmeans output (d <- lsmeans(paramaters))
d <- summary(d)$lsmeans[c("lsmean", "lower.CL", "upper.CL")]

library(ggplot2)
ggplot(d, aes(time)) +
    geom_line(aes(y = lsmean)) +
    geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL),
                  width = 0.2) +
    geom_point(aes(y = lsmean), size = 3, 
               shape = 21, fill = "white") +
    labs(x = "Time", y = "ls mean",
         title = "ls mean result over time") +
    theme_bw()

Dirty solution

答案 1 :(得分:0)

总而言之,将为您提供混合模型的估计和绘图的整个代码是:

## random slope model
summary(model <- lme(outcome ~ time, random = ~1+time|ID, data = data, 
na.action = na.exclude, method = "ML"))

## pairwise comparisons of timepoints
install.packages("lsmeans")
library(lsmeans)
lsmeans(model, pairwise~time, adjust="tukey")

### Draw the picture
d <- summary(lsmeans(model, ~time))

library(ggplot2)
ggplot(d, aes(time)) +
  geom_line(aes(y = lsmean, group = 1)) +
  geom_errorbar(aes(ymin = lower.CL, ymax = upper.CL), width = 0.2) +
  geom_point(aes(y = lsmean), size = 3, shape = 21, fill = "white") +
  labs(x = "Time", y = "ls mean", title = "ls mean result over time") +
  theme_bw()