首页 > 解决方案 > 对于`Petal.Length`的固定值和`Species`,如何绘制`Sepal.Length`和`Sepal.Width`之间的关系?

问题描述

我正在运行 LME,我想绘制我的响应变量和我的一个预测变量之间的关系,保持另一个预测变量不变,并通过ID(被认为是随机因素)。

同样,使用iris数据框示例,它将对应于:

library(nlme)
library(ggplot2)

df <- iris[,c("Sepal.Length","Sepal.Width","Petal.Length","Species")]

mod <-nlme::lme(Sepal.Length ~ Sepal.Width * Petal.Length, random= ~ 1|Species, data = df,method="REML")

如您所见,其中species用作随机因素。在这个例子中,我想绘制的是 和 之间的线性关系,并Sepal.Length保持Sepal.Width不变。Petal.Lengthspecies

我试过这个:

Plot <- ggplot(df, aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) + 
  geom_point(size=1.7,alpha=0.6) +
  geom_line(aes(y=predict(mod, Petal.Length=mean(iris$Petal.Length)), group=Species), size=2.1)
Plot

在此处输入图像描述

但是,情节与我这样做的情节相同:

Plot <- ggplot(df, aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) + 
  geom_point(size=1.7,alpha=0.6) +
  geom_line(aes(y=predict(mod), group=Species), size=2.1)
Plot

所以,我没有保持不变Petal.Length。我也知道我没有保持不变Petal.Length,因为我没有得到每个物种的直线。也就是说,Petal.Length是什么使线条变得不规则,因为当我在我的模型中不考虑Petal.Length时,我得到了这个:

mod.b <-nlme::lme(Sepal.Length ~ Sepal.Width, random= ~ 1|Species, data = df,method="REML")

Plot <- ggplot(df, aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) + 
  geom_point(size=1.7,alpha=0.6) +
  geom_line(aes(y=predict(mod.b), group=Species), size=2.1)
Plot

在此处输入图像描述

那么,有没有人知道如何在通过随机因子Petal.Length为模型绘制线性预测时保持一个预测变量 ( ) 不变?LME

我将不胜感激任何帮助

标签: rggplot2mixed-models

解决方案


我想这就是你要找的:

library(ggplot2)
newdf <- df
newdf$Petal.Length <- ave(newdf$Petal.Length, newdf$Species)

ggplot(df, aes(x=Sepal.Width, y=Sepal.Length, colour=Species)) + 
 geom_point(size=1.7,alpha=0.6) +
 geom_line(aes(y=predict(mod, newdf), group=Species), size=2.1)

在此处输入图像描述

笔记:

  • predict以错误的方式使用该功能。您需要添加一组全新的数据,而不仅仅是一列。此外,您编写新列的方式是错误的,因为您实际上为predict函数提供了一个名为的参数,该参数Petal.Length属于...,因此被忽略。
  • 我用 计算了每个组的平均值ave,否则您的结果将没有意义。如果您尝试通过Petal.Length以这种方式计算平均值来绘制图形newiris$Petal.Length <- mean(newiris$Petal.Length),您将明白我的意思。

当你写:

ave(newdf$Petal.Length, newdf$Species)

ave计算由newdf$Petal.Length以下定义的每个组的平均值newdf$Species


推荐阅读