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)
Thus, curve fitting involves finding the best polynomials to fit the data; for example, for a quadratic polynomial in the form ax2 + bx + c, it means finding the values of a, b, and c that yield the best fit.
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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With