2

Using the fda package I have created the fd object called "curve":

splinebasis = create.bspline.basis(rangeval = c(0,100), 
                                     nbasis = 23,         
                                     norder = 4) 
curve = smooth.basis(x, y, splinebasis)$fd

At this point I can easily plot my fd object through the command:

plot(curve)

Single curve plot

Obtaining a fine result.

What I would like to do, is to plot the object using the ggplot2 package, but unfortunatelly I have no clue how to code the ggplot2 s.t. it uses the basis and coefficient to return the continuous curve*.

  • I have actually done it using eval.fd, but I wish to plot the actual B spline function using ggplot, instead of some new generated discrete points.
chemdork123
  • 12,369
  • 2
  • 16
  • 32
  • 2
    Your code is not reproducible: `Error in smooth.basis(x, y, splinebasis) : object 'y' not found`. – Axeman Sep 04 '20 at 20:32

1 Answers1

2

Here is a simple solution using predict from the fda package.

library(fda)
set.seed(1)
x <- 0:100
y <- cumsum(rnorm(101))

splinebasis <- create.bspline.basis(rangeval = c(0,100), 
                                     nbasis = 23,         
                                     norder = 4) 
curve <- smooth.basis(x, y, splinebasis)

# Plot using base graphic engine
plot(curve$fd)

enter image description here

# Plot using ggplot2
library(ggplot2)   
xx <- seq(0,100,0.1)
df <- data.frame(x=xx, yhat = predict(curve, newdata=xx))
ggplot(data=df, aes(x=x, y=yhat)) +
  geom_line() +
  geom_hline(aes(yintercept=0), linetype=2) +
  labs(x="time", y="value") +
  theme_bw()

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58