[R] how do I plot a regression curve with the data?

andrew andrewjohnroyal at gmail.com
Wed Oct 28 02:02:13 CET 2009

Hi Ken,

Perhaps something like

lines(sort(x), fit$fitted.values[order(x)])

should do what I think you want.  I think you have to be a bit careful
on the ordering of the fitted values so that they match up with the
order of the x variable, otherwise you get an odd looking line plot.



On Oct 28, 5:42 am, Ken Ervin <ervinj... at gmail.com> wrote:
> I have a data set of 6 or so ordered pairs, and I've been able to graph
> them and have decided to use a high-order polynomial regression.  I've
> used the following piece of code:
> regression <- function(x,y) {
>     x <- c(insert_numbers_here)
>     y <- c(insert_other_numbers_here)
>     fit <- lm(y ~ x + I(x^2) + I(x^3) + I(x^4) + I(x^5) + I(x^6) +
> I(x^7) + I(x^8) + I(x^9))
>     summary(fit)
> This gives me the coefficients for the regression very nicely, but I
> would like to plot both the data and the regression curve together.  How
> do I plot that regression curve as a function, and can I put it on the
> same set of axes as my data scatter plot?
> Thanks in advance for your help!
> -KE
> ______________________________________________
> R-h... at r-project.org mailing listhttps://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guidehttp://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list