使用包ggplot2和iris,我想绘制一个带有拟合回归线的散点图。
library(ggplot2)
ggplot(data=iris, aes(x = Petal.Width, y = Petal.Length,color=Species)) +
geom_point(shape=1) +
stat_smooth(method = "lm",formula= 'Petal.Length ~ Petal.Width+I(Petal.Width^2)+SaleType+Petal.Width*Species', data=iris,
aes(x = Petal.Width, y = Petal.Length,color=Species))
**Warning message:
Computation failed in `stat_smooth()`:
variable lengths differ (found for '(weights)')**
我正在考虑得到这个警告的原因,我有两个自变量,但是现在R无法读取在stat_smooth中按颜色分割的Species。如何绘制两条与plot(Petal.Width,fitted(fit))
相同的线。另外,如果我有另一个由同一组数据拟合的回归模型,但log(y),fit<-lm(log(Petal.Length)~Petal.Width+Species+Petal.Width*Species,data=iris).
我可以将两个回归模型的绘制放在同一个图形中吗?
我不认为将变换后的回归与原始值组合在同一规模上是不合适的。相反,这些应该绘制在不同的数字上。使用iris
数据集,您可以绘制原始数据,如下所示:
ggplot(data=iris, aes(color=Species)) +
geom_point(aes(x = Petal.Width, y = Sepal.Width)) +
stat_smooth(method = "lm", aes(x = Petal.Width, y = Sepal.Width,color=Species))
然后将Sepal.Width
转换为另一个变量:
iris$LogSepal.Width <- log(iris$Sepal.Width)
然后绘制变换后的变量。我希望这有帮助。
ggplot(data=iris, aes(color=Species)) +
geom_point(aes(x = Petal.Width, y = LogSepal.Width)) +
stat_smooth(method = "lm", aes(x = Petal.Width, y = LogSepal.Width,color=Species))