r - 对于`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.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
但是,情节与我这样做的情节相同:
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
我将不胜感激任何帮助
解决方案
我想这就是你要找的:
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
推荐阅读
- php - 如何在 PHP 中将一种日期格式更改为另一种日期格式
- django - Django:在我从具有动态数据的视图中呈现模板后,模板保持静态并且在将数据添加到数据库时不会更改
- python - 使用在 Flask 中运行的连接将 SQL 转换为 Sqlalchemy Select
- r - 按条件过滤数据帧,包括该条件之后的数据
- css - 反应原生的CSS线性渐变
- javascript - 我的 2D 光线追踪功能有什么问题?
- android - 我的 Json 类需要很长时间才能加载
- python-3.x - Python3.x:在相同的 x 处减去 y 值
- javascript - Axios POST promise not working as expected
- php - 如何用“而不是”显示表单字段属性?