对于固定值“ Petal.Length”和“种类”,如何绘制“ 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.LengthSepal.Width之间的线性关系,并保持Petal.Length并保持species不变。

我已经尝试过了:

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

enter image description here

但是,剧情和我做的一样:

Plot <- ggplot(df,alpha=0.6) +
  geom_line(aes(y=predict(mod),size=2.1)
Plot

所以,我没有保持常数Petal.Length。我也知道我没有保持常数Petal.Length,因为我没有为每个物种得到一条直线。也就是说,Petal.Length的不适当之处在于使行不规则,因为当我在模型中不考虑Petal.Length时,我会得到:

mod.b <-nlme::lme(Sepal.Length ~ Sepal.Width,method="REML")

Plot <- ggplot(df,alpha=0.6) +
  geom_line(aes(y=predict(mod.b),size=2.1)
Plot

enter image description here

因此,有人通过随机因子为Petal.Length模型绘制线性预测时,有谁知道如何保持一个预测变量(LME)恒定吗?

我将不胜感激

解决方法

我认为这就是您要寻找的东西

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)

https://github.com/rune1979/python_simple_password_manager

注意:

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

撰写时:

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

avenewdf$Petal.Length定义的每个组计算newdf$Species的平均值。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...