Reputation: 3376
Suppose that I have these data set:
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)
The ggplot
function just fit a linear model that suits for y
. How can we add a quadratic model for z
to the above function in addition to the linear model.
I look for a better way than this post: ggplot2 - plot multiple models on the same plot
Upvotes: 1
Views: 1425
Reputation: 3376
The following code has solved my problem:
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)
Upvotes: 0
Reputation: 4180
Still not entirely sure how you mean, but I imagine this would be a step in the direction that you want:
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)
In your data you have one group (index = 1) that is connected by a linear function, and the other by a quadratic function. If you specify formula y ~ x, a straight regression lines is fitted for both groups, and this is not what you want, correct?
The code above produces two layers, first one your initial layer with two straight lines, the second one contains one straight line and one quadratic curve. Since the linear group is the same in both graphs you see only three lines. If you want to remove the portion with two straight lines, delete the second code line, so that only formula y ~ poly(x,2)
remains. poly(x,2)
is equivalent to x + I(x^2)
which reflects the mathematical formula of y = x + x².
I have removed the geom_point()
from the code so that it does not obscure the results. Feel free to include it back. Hope this is what you need.
Upvotes: 1