【问题标题】:plot lmer result in faceted ggplot绘制 lmer 结果为多面 ggplot
【发布时间】:2015-04-26 05:25:07
【问题描述】:

我正在分析一些重复测量的药物试验数据,但我不确定在使用多面 ggplots 时如何绘制 lmer 结果。我已经从主数据集中绘制了各个斜率的初始图,但我正在按性别分别进行 lmer 分析。

使用公开数据,与我的四个治疗组相比,只有两个治疗组,这是下面可复制的示例。它使用reshape2lme4ggplot2 包。

CatAnx <- read.fwf(file=("http://www.stat.ufl.edu/~winner/data/cats_anxiety1.dat"),
               widths=c(-6,2,-5,3,-5,3,-7,1,-7,1,-7,1,-7,1,-7,1,-6,2,-6,2,-6,2,-6,2,-6,2))
colnames(CatAnx) <- c('ID','Weight','Age_Months','Gender','Environment','Origin','Treatment','Result','EmoTime1','EmoTime2',
                  'EmoTime3','EmoTime4','EmoTime5')
library("reshape2")
CatAnxRM <- melt(CatAnx, id.vars=c("ID", "Gender", "Treatment"), measure.vars=c("EmoTime1", "EmoTime2", "EmoTime3",
                                                                            "EmoTime4", "EmoTime5"))
CatAnxRM$Sex <- with(CatAnxRM, ifelse(Gender==1, "Neut Female", ifelse(Gender==2, "Neut Male", "Whole Female")))
CatAnxRM$Time <- with(CatAnxRM, ifelse(variable=="EmoTime1", 1, ifelse(variable=="EmoTime2", 2, ifelse(variable=="EmoTime3", 3,
                                  ifelse(variable=="EmoTime4", 4,5)))))
CatAnxRM.Male <- subset(CatAnxRM, Gender=="2")
library("lme4")
Male.lmer <- lmer(value ~ Treatment * Time + (Time + 1|ID), data=CatAnxRM.Male)
library("ggplot2")
AnxScores<-ggplot(CatAnxRM, aes(Time, value, colour=Sex))+
geom_line(aes(group = ID))+
labs(x="Time Anxiety Measured", y="Anxiety Score", title="Effect of Zylkene on Anxiety")+ 
facet_grid(. ~ Treatment)
AnxScores

关于数据集is here的信息。

如何从 lmer 在两个方面绘制正确的摘要线,这两个方面因Treatment 而不同?

在我的现实生活示例中,我还将分析女性,因此每个方面将绘制两组线。

【问题讨论】:

    标签: r ggplot2 facet lmer


    【解决方案1】:

    使用截距(例如int)和斜率(slo)变量创建一个数据框(例如lines.df),其中df的每一行对应一个方面,然后在顶部绘制:

    + geom_abline(aes(intercept = int, slope = slo), data = lines.df)
    

    【讨论】:

    • 因为我将在每个方面有两行,我是否需要在lines.df 中添加一个性别指示器,以便我可以获得每个方面的正确行数?
    • 您可以将 sex 添加到 lines.df 并在每个方面有两行,每个方面有一个性别,然后添加例如colour=sexlinetype=sexaes 或添加第二个数据框并使用额外的代码行调用它
    • 我要在每个方面绘制所有四行,我如何指示 ggplotlines.df 中的哪一行来绘制每个方面?这是四行,而不是两行,因为我是在我的实际工作中实现的,而不是示例。
    • 我想我通过添加 Treatment 的值来修复它,现在它知道在哪个方面绘制每条线。
    【解决方案2】:

    “正确的摘要行”是什么意思并不完全清楚,但我已根据您的数据调整了 this answer 中的代码。这是你需要的输出吗?

    newdata <- with(CatAnxRM.Male, expand.grid(Treatment=unique(Treatment),
                                               Time=unique(Time), Sex = unique(Sex),
                                               ID=unique(ID)))
    
    newdata$pred <- predict(Male.lmer, newdata)
    
    p <- ggplot(newdata, aes(x=Time, y=pred, colour=Sex, group=ID))
    p + geom_line() + ggtitle("Varying Slopes") + 
        facet_grid(. ~ Treatment)
    

    并得到以下输出

    【讨论】:

    • 嗨 r.bot,我要的是原始的 facets 图,lmer 结果的平均线在每个 facet 上重叠。我试图在原始线条之上显示组平均值(接受治疗的性行为),以便我可以了解整体变化。因此,如果它是 OLS 回归,则重叠图将是最佳拟合线,位于各个斜率之上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多