首页 文章

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

提问于
浏览
16

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

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

但是,在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])

我收到以下错误:

geom_smooth: Only one unique x value each group.Maybe you want aes(group = 1)?

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

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

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

2 回答

  • 1

    错误消息几乎是不言自明的:将 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))
    

    enter image description here

  • 23

    仅供参考,使用简单的 qplot 接口也可以遇到(并修复)此错误 ggplot2

    对于少数人来说错误信息不够解释:-) . 在这种情况下,关键是仅包括建议美学的内容

    library(ggplot2)
    qplot(factor(Sepal.Length), Sepal.Width, geom = c("smooth"), data= iris)
    # error, needs aes(group=1)
    qplot(factor(Sepal.Length), Sepal.Width, geom = c("smooth"), group = 1, data= iris)
    

相关问题