12

I'm trying to add a fitted quadratic curve to a plot.

abline(lm(data~factor+I(factor^2)))

The regression which is displayed is linear and not quadratic and I get this message:

Message d'avis : In abline(lm(data ~ factor + I(factor^2)), col = palette[iteration]) : utilisation des deux premiers des 3 coefficients de régression

which means:

Use of the first 2 of the 3 regression coefficients

When running only the lm() function I don't get any messages.

Here is a sample data:

factor <- 1:7
data <- c(0.1375000,0.2500000,0.3416667,0.4583333,0.7250000,0.9166667,1.0000000)
Arun
  • 116,683
  • 26
  • 284
  • 387
Remi.b
  • 17,389
  • 28
  • 87
  • 168

3 Answers3

11

Instead of using abline, use fitted, which gives you a vector the same length as your input of the predictions:

fitted(lm(data~factor+I(factor^2)))
#         1         2         3         4         5         6         7 
# 0.1248016 0.2395833 0.3699405 0.5158730 0.6773810 0.8544643 1.0471230 

Thus, something like:

plot(factor, fitted(lm(data~factor+I(factor^2))), type="l")
Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • I think it's helpful to know that this works more consistently (i.e., with numeric variables) when you `sort` both X and Y variables in `plot` (i.e., the original X value and the fitted data) . --> `plot(sort(x), sort(fitted(lm(y~x+I(x^2)))), type = 'l')` – theforestecologist Jan 25 '23 at 04:24
3

I couldn't get answers so far to work, as dataset I used has x-values which are not increasing (as stated by David Robinson above). Here's how I solved it...

require(ISLR)
plot(mpg~horsepower, data=Auto)

# fit the model
glm.fit = glm(mpg~poly(horsepower,2), data=Auto)

# create 100 x-values based on min/max of plotted values
minMax = range(Auto$horsepower)
xVals = seq(minMax[1], minMax[2], len = 100) 

# Use predict based on a dataframe containing 'horsepower'
yVals = predict(glm.fit, newdata = data.frame(horsepower = xVals))

lines(xVals, yVals)
bwb
  • 163
  • 1
  • 5
Mike
  • 31
  • 1
0

thanks for all these valuable answer. Be carefull:

Use

Use predict based on a dataframe containing 'horsepower'

yVals = predict(glm.fit, newdata = data.frame(horsepower=xVals)

Use predict based on a dataframe containing 'horsepower'

yVals = predict(lm.fit, newdata = data.frame(horsepower=xVals)

lm.fit is a function

MLavoie
  • 9,671
  • 41
  • 36
  • 56
Souleymane
  • 11
  • 1