2012-06-06 86 views
15

當使用標準的R圖形添加線性模型趨勢線的箱線圖使用:添加一個簡單的LM趨勢線到ggplot箱線圖

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)? 

併線不會出現在我的陰謀。

在這兩種情況下使用的模型都是相同的。如果任何人都能指出我出錯的地方,那會很好。

編輯:以虹膜數據集爲例。

回答

22

該錯誤消息是相當多的不言自明的:添加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

+0

啊好吧,我不知道配方的內容。感謝您解決這個問題。 – JPD

+0

請注意,我沒有「替換」公式。公式不是必需的,所以我刪除了它。 – Andrie

+9

Pet peeve:「錯誤信息是自我解釋的」。如果這是自我解釋,OP就不會問這個問題了。 – Twitch

1

僅供參考,也可以使用簡單的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)