Search code examples
rplotspline

Add markers to given values of x in a plot


I am working with spline functions and I want to plot the basis and add markers showing the position of the knots. I've tried adding a vertical line using abline(v=knots) but the result is not nice and if I am dealing with many knots it's quite distracting. I leave you an image below that shows what I want to do. This is my code where I use the bs function from the package splines.

library(splines)
x <- seq(0, 1, length.out=1000)  
B <- bs(x, knots=seq(0, 1, length=20)[-c(1, 20)], Boundary.knots=c(0, 1), degree=2) 
matplot(x, B, type="l", lty=1, col="red")

This is what I would like to obtain (see those little "x" showing the position of the knots?). This is merely an example, if you have some idea to show the position of the knots in such a way that the result is non visually messy I would be glad to hear it. enter image description here

I really appreciate any help


Solution

  • First, store the knot values from the attributes of B. And then use the low-level graphics function points() to add markers which the symbol can be adjusted by the argument pch.

    knot <- c(0, attr(B, "knots"), 1)
    points(knot, rep(0, length(knot)), pch = "x")
    

    enter image description here