Search code examples
rplot

lines() command now creating weird connected plot?


I'm trying to replot data with the same code which looked fine the first time but now the lines are all oddly connected. Here's the code:

lines(x, predict(gam.ns), col=1, lwd=2)

And examples of what I'm getting now enter image description here

And what I was getting before (with additional data plotted) and would like to have again enter image description here

What am I missing? Thanks!


Solution

  • lines() connects points in order. Your data set was previously sorted in order of x, this version isn't. You can either go back upstream and order them, or:

    ox <- order(x)
    lines(x[ox], predict(gam.ns)[ox], col=1, lwd=2)
    

    x[ox] is identical to sort(x), but you need ox because you want to arrange the predicted values in the same order ...