将简单的lm趋势线添加到ggplot boxplot

JPD*_*JPD 17 r ggplot2 boxplot trendline

使用标准R图形将线性模型趋势线添加到箱线图时,我使用:

boxplot(iris[,2]~iris[,1],col="LightBlue",main="Quartile1 (Rare)")
modelQ1<-lm(iris[,2]~iris[,1])
abline(modelQ1,lwd=2)
Run Code Online (Sandbox Code Playgroud)

但是,在ggplot2中使用它时:

a <- ggplot(iris,aes(factor(iris[,1]),iris[,2]))
a + geom_boxplot() +
geom_smooth(method = "lm", se=FALSE, color="black", formula=iris[,2]~iris[,1])
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?
Run Code Online (Sandbox Code Playgroud)

这条线没有出现在我的情节中.

这两种情况中使用的模型是相同的.如果有人能指出我哪里出错了,那就太好了.

编辑:使用虹膜数据集作为示例.

And*_*rie 24

错误消息几乎是不言自明的:添加aes(group=1)geom_smooth:

ggplot(iris, aes(factor(Sepal.Length), Sepal.Width)) +
  geom_boxplot() +
  geom_smooth(method = "lm", se=FALSE, color="black", aes(group=1))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 宠儿:"错误信息是自我解释的".如果它是自我解释的OP将不会开始提出问题. (9认同)