Skip to content

Plotting a quadratic line on top of an xy scatterplot

3 messages · Josh B, Joshua Wiley, jjap

#
Hi Josh,

This is by no means the fanciest solution ever, but as there are
predict methods for many types of models in R, I thought I would show
it this way.

## fit the model
model <- lm(probability ~ poly(temperature, 2), data = x)

## create line values
dat <- data.frame(temperature = seq(min(x$temperature, na.rm = TRUE),
max(x$temperature, na.rm = TRUE), by = .01))
## add predicted y values
dat$yhat <- predict(model, dat)

## plot data
plot(probability ~ temperature, data = x)
## add predicted line
lines(x = dat$temperature, y = dat$yhat, type = "l")

Hope this helps,

Josh
On Mon, Apr 11, 2011 at 12:29 PM, Josh B <joshb41 at yahoo.com> wrote:

  
    
#
Hi,

Is it just me or it appears the "temperature" and "probability" should be
reversed? 
--------
Anyhow it should help you to assign your model to a variable (as Joshua did
with his own suggestion)

yourmodel <-lm(x[,2] ~ x[,1] + I(x[,1]^2)) # again, taking literally the way
you formulated it...

And you could then access the coefficients individually:

c <- coef(yourmodel)[1] # for the intercept 
b <- coef(yourmodel)[2] 
a <- coef(yourmodel)[3] 

To build yourself a vector of predicted y-values based on a vector of
x-values ("dat" as per Joshua's post)
and pass them to the "lines" function to be plotted over your existing plot.

This is less convenient than using the "predict" but sometimes it helps to
do the arithmetic at a lower level.
HTH


--
View this message in context: http://r.789695.n4.nabble.com/Plotting-a-quadratic-line-on-top-of-an-xy-scatterplot-tp3443018p3443693.html
Sent from the R help mailing list archive at Nabble.com.