rplotstatisticssplinepiecewise

Issue ploting data and linear basis using matlines


I'm trying to get a linear basis to be plotted one the same graph as my data points and predicted model however I am not able to figure out how to combine the two using the matlines and matplot functions in R. Here is the code that I am using,

require(faraway)
require(splines)
data(exa, package="faraway")

matplot(bs(exa$x,10,degree=1),type="l",ylab="")
lmod <- lm(y ~ bs(x,10,degree=1),exa)
plot(y ~ x, exa, col=gray(0.75))
lines(predict(lmod) ~ x, exa, lty=2)
matlines(bs(exa$x,10,degree=1),predict(lmod) ,type="l",ylab="")

Which produces the following two plots, enter image description here

The first plot is what I expect it to be however the second plot seems very distorted and I cannot figure out how to get the second plot to display properly. It appears that the axis is somehow distorted as I am expecting the linear basis to be plotted on the x-axis. I am expecting the second plot to appear something similar to this, enter image description here

Any help is greatly appreciated.


Solution

  • You're probably just confused by the formula notation. In the plotting sequence you always want the same x=.

    with(exa, plot(x=x, y=y, col=gray(0.75), pch=20))
    with(exa, lines(x=x, y=predict(lmod), lty=2))
    with(exa, matlines(x=x, y=bs(x, 10, degree=1), type="l", ylab=""))
    

    enter image description here