# [R] Plotting a quadratic line on top of an xy scatterplot

Joshua Wiley jwiley.psych at gmail.com
Tue Apr 12 03:12:24 CEST 2011

```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))
dat\$yhat <- predict(model, dat)

## plot data
plot(probability ~ temperature, data = x)
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:
> Dear Listserv,
>
> Here is my latest in a series of simple-seeming questions that dog me.
>
> Consider the following data:
>
> 0.11 9.4
> 0 2.3
> 0.38 8.7
> 0.43 9.2
> 0.6 15.6
> 0.47 8.7
> 0.09 12.8
> 0.11 9.4
> 0.01 7.7
> 0.83 8
> 0.65 9.3
> 0.05 7.4
> 0.34 10.1
> 0.02 4.8
> 0.07 9.1
> 0.6 15.6
> 0.01 8.4
> 0.9 9.6
> 0.83 8
> 0.12 8.4
> 0.01 8
> 0 5
> 0.11 9.7
> 0.41 7.4
> 0.05 9.4
> 0.09 8.3
> 0 6.1
> 0.12 8.4
> 0.73 7.8
> 0 4.2"), header = TRUE, as.is = TRUE)
> closeAllConnections()
>
> I modeled the relationship: Probability = f(Temperature), i.e., probability as a
> function of temperature.
>
> I found that there is a significant quadratic term in the model:
>
> summary(lm(x[,2] ~ x[,1] + I(x[,1]^2)))
>
> Now the question is: how do I plot it?
>
> I can do this:
> plot(x[,2] ~ x[,1])
>
> ...but I would also like to add a line corresponding to the quadratic function.
> In other words, I want to visually show the relationship among the variables
> that is being modeled. How do I do it? I think the curve() command will be used,
> but I don't know how to employ it.
>
> Thanks very much in advance.
>
> Sincerely,
> -----------------------------------
> Josh Banta, Ph.D
> Center for Genomics and Systems Biology
> New York University
> 100 Washington Square East
> New York, NY 10003
> Tel: (212) 998-8465
> http://plantevolutionaryecology.org
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>

--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/

```