0

I'm doing a polynomial regression and I want to plot it.

My code is the following:

to create polynomial regression to degree 1

mreg6=lm(user_Score~poly(year_of_Release,1)) 

to create plot

plot(year_of_Release~user_Score, col='gray')

to create line

lines(sort(year_of_Release),predict(mreg6)[order(year_of_Release)],col='red')

to create legend

legend('topright',lty=1:2,col=c('red'),c('degree 1'))

When I run the code, there is no error but the line does not appear on graph. Do any of you know what I might be doing wrong?

Ben
  • 28,684
  • 5
  • 23
  • 45
  • 1
    Welcome to SO! It might help to have example data to reproduce this problem (e.g., using `dput()`). https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Ben Oct 13 '19 at 16:48
  • 1
    The formula interface `plot(year_of_Release ~ user_Score, col='gray')` in `plot` treats the first variable as `y` and the second as `x`, so `year_of_Release` is plotted on the y-axis even though it's the `x` variable in the regression. If you look at your graph, you'll likely see the variables are not on the axes you expected. Either reverse the order or change to `plot(year_of_Release, user_Score)` – eipi10 Oct 13 '19 at 16:53
  • To complete the explanation, `lines` is indeed plotting a line, but since the variables are on the correct axes and have different ranges, the location where the line is "plotted" is not within the range of the x and y limits of the graph. – eipi10 Oct 13 '19 at 17:01

1 Answers1

0

I found my answer: I was putting ~ instead of , in plot() so it was giving me another regression.

  • 1
    It wasn't giving you a regression, it was plotting the columns in reverse order (since the formula interface is `y ~ x`, as compare with `x, y`). See the second comment below your question for details. – eipi10 Oct 13 '19 at 17:54