I have a data frame x1
, which was generated with the following piece of code,
x <- c(1:10)
y <- x^3
z <- y-20
s <- z/3
t <- s*6
q
I suppose you're looking for geom_smooth
. If you call this function with the argument method = "lm"
, it will calculate a linear fit for all groups:
ggplot(xm, aes(x = x, y = value, color = cols)) +
geom_point(size = 3) +
labs(x = "x", y = "y") +
geom_smooth(method = "lm", se = FALSE)
You can also specify a quadratic fit with the poly
function and the formula
argument:
ggplot(xm, aes(x = x, y = value, color=cols)) +
geom_point(size = 3) +
labs(x = "x", y = "y") +
geom_smooth(method = "lm", se = FALSE, formula = y ~ poly(x, 2))
To extract the corresponding regression coefficients, you can use this approach:
# create a list of coefficients
fits <- by(xm[-2], xm$cols, function(i) coef(lm(value ~ x, i)))
# create a data frame
data.frame(cols = names(fits), do.call(rbind, fits))
# cols X.Intercept. x
# y y -277.20000 105.40000
# s s -99.06667 35.13333
# t t -594.40000 210.80000
If you want a quadratic fit, just replace value ~ x
with value ~ poly(x, 2)
.