[R-sig-eco] lines() adds extra line

Sarah Goslee sarah.goslee at gmail.com
Mon Jan 24 19:15:26 CET 2011


R is doing just as you asked. If you look at the middle of c(x, x) the
x values jump from 10 to -10 and R draws the line segment connecting
them, as it's been told.

> c(x,x)[195:205]
 [1]   9.4   9.5   9.6   9.7   9.8   9.9  10.0 -10.0  -9.9  -9.8  -9.7

You might rather have:
> x2.rev <- c(x, rev(x))
> x.rev.pred <- predict(lm(dataBoth.poly ~ x2.rev + I(x2.rev^2)+I(x2.rev^3)+I(x2.rev^4)+I(x2.rev^5)+I(x2.rev^6)))
> plot(x2.rev, x.rev.pred, type="l")

Sarah


On Mon, Jan 24, 2011 at 1:04 PM, Jane Shevtsov <jane.eco at gmail.com> wrote:
> I'm trying a bit of an experiment with polynomial curve fitting (don't
> worry, I wouldn't do this to actual data -- it's just a toy model for
> a specific question). When I generate a linear model of the data and
> plot it using plot(), everything works fine. But when I use plot(...,
> type="l") or lines(), I get an extra line connecting two points. How
> do I stop this from happening?
>
> Here's the code:
> x = seq(-10, 10, by=0.1)
> data1poly <- 0.1*x + 0.2*x^2 + 0.3*x^3 + 0.4*x^4 + 0.5*x^5 + 0.6*x^6 +
> 0.7 + rnorm(length(x),1E-3, 1E-4)
> data2poly <- 0.1*x + 0.2*x^2 + 0.3*x^3 + 0.4*x^4 + 0.5*x^5 + 0.6*x^6 -
> 1 + rnorm(length(x), 1E-3, 1E-4)
> dataBoth.poly <- c(data1poly, data2poly)
> #Works well
> plot(c(x,x), predict(lm(dataBoth.poly ~ c(x,x) +
> I(c(x,x)^2)+I(c(x,x)^3)+I(c(x,x)^4)+I(c(x,x)^5)+I(c(x,x)^6))))
> #Adds extra line
> plot(c(x,x), predict(lm(dataBoth.poly ~ c(x,x) +
> I(c(x,x)^2)+I(c(x,x)^3)+I(c(x,x)^4)+I(c(x,x)^5)+I(c(x,x)^6))),
> type="l")  #or
> lines(c(x,x), predict(lm(dataBoth.poly ~ c(x,x) +
> I(c(x,x)^2)+I(c(x,x)^3)+I(c(x,x)^4)+I(c(x,x)^5)+I(c(x,x)^6))))
>
> Thanks,
> Jane
>
> --

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-sig-ecology mailing list