1

假设我有这些数据集:

x <- 1:100
y <- 2 +  70* x
z <- 2 + x^2
index <- c(rep(1,100),rep(2,100))

x <- c(x,x)
t<-  c(y,z)
data <- data.frame(x,t,index)

data[,2]= data[,2] + rnorm(200,500,400)

ggplot(data, aes(x = x, y = t, colour = factor(index))) + geom_point() + stat_smooth(method = "lm", formula = y ~ x, se = FALSE)

ggplot函数恰好适合适合的线性模型yz除了线性模型之外,我们如何为上述函数添加二次模型。

我寻找比这篇文章更好的方法: ggplot2 - plot multiple models on the same plot

4

2 回答 2

1

仍然不完全确定您的意思,但我想这将是朝着您想要的方向迈出的一步:

ggplot(data, aes(x = x, y = t, colour = factor(index))) + 
  stat_smooth(method = "lm", formula = y ~ x, se = FALSE) +
  stat_smooth(method = "lm", formula = y ~ poly(x,2), se = FALSE)

在您的数据中,您有一组(索引 = 1)由线性函数连接,另一组由二次函数连接。如果您指定公式 y ~ x,则会为两组拟合直线回归线,这不是您想要的,对吗?

上面的代码产生两层,第一层是你的初始层,有两条直线,第二层包含一条直线和一条二次曲线。由于两个图中的线性组相同,因此您只看到三条线。如果要删除有两条直线的部分,请删除第二条代码行,以便仅y ~ poly(x,2)保留公式。poly(x,2)相当于x + I(x^2)反映了y = x + x²的数学公式。

我已经geom_point()从代码中删除了,这样它就不会掩盖结果。随意将其包含回来。希望这是你需要的。

于 2013-07-05T13:21:49.637 回答
0

以下代码解决了我的问题:

ggplot() + layer (data = data[1:100,], mapping=aes(x = x, y = t,colour = factor(index)),stat = "identity") + 
 stat_smooth(data=data[1:100,], mapping = aes(x = x, y = t), method = "lm", formula = y ~ x, se = FALSE) + 
 layer(data=data[100:200,], mapping=aes(x = x, y = t,colour = factor(index)), stat = "identity") + 
 stat_smooth(data = data[100:200,], mapping = aes(x = x, y = t), method = "lm", formula = y ~ poly(x,2), se = FALSE)
于 2013-07-07T04:12:18.177 回答