19

I would like to fit my data using spline(y~x) but all of the examples that I can find use a spline with smoothing, e.g. lm(y~ns(x), df=_).

I want to use spline() specifically because I am using this to do the analysis represented by the plot that I am making.

Is there a simple way to use spline() in ggplot?

I have considered the hackish approach of fitting a line using

geom_smooth(aes(x=(spline(y~x)$x, y=spline(y~x)$y))

but I would prefer not to have to resort to this.

Thanks!

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
David LeBauer
  • 31,011
  • 31
  • 115
  • 189

2 Answers2

30

is this what you want?

n <- 10
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y)) + geom_point() + 
  geom_line(data=data.frame(spline(d, n=n*10)))
kohske
  • 65,572
  • 8
  • 165
  • 155
  • that is exactly what I was looking for; nice and simple. thanks – David LeBauer Dec 22 '10 at 01:04
  • 1
    what if I want to draw two lines, e.g. for the `x1,y1` and `x2,y2` in `d<-data.frame(x1=1:n, y1=rnorm(n), x2=1:n+0.5, y2=runif(10))`? I am having trouble with the line `geom_line(aes(x1,y1), data=data.frame(spline(x1,y1)))` – David LeBauer Dec 22 '10 at 16:37
  • 1
    the answer to the above is: `geom_line(aes(d$x1,d$y1), data=data.frame(spline(x1,y1)))`, although I am not sure why... – David LeBauer Dec 22 '10 at 16:40
2

Alternatively, with ggformula https://rdrr.io/cran/ggformula/man/geom_spline.html, you can call ggformula::stat_spline() directly within ggplot().

library(ggplot2)
library(ggformula)

n<-1000
d <- data.frame(x = 1:n, y = rnorm(n))
ggplot(d,aes(x,y))+
  # geom_point()+
  stat_spline()

enter image description here

Note: OP asked specifically about using spline(). stat_spline() {ggformula} calls smooth.spline() {stats}, which might not be exactly the same implementation as spline() {stats} but think it may still be a useful answer here for others.

Dylan_Gomes
  • 2,066
  • 14
  • 29