Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use spline() with ggplot?

Tags:

r

ggplot2

spline

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!

like image 748
David LeBauer Avatar asked Dec 21 '10 22:12

David LeBauer


People also ask

What does spline do in R?

Splines provide a way to smoothly interpolate between fixed points, called knots. Polynomial regression is computed between knots. In other words, splines are series of polynomial segments strung together, joining at knots. In case of spline regression we divide datasets into bins.

What does Geom_smooth do in R?

Key R function: geom_smooth() for adding smoothed conditional means / regression line. Key arguments: color , size and linetype : Change the line color, size and type. fill : Change the fill color of the confidence region.

What is a spline variable?

A spline is a continuous function which coincides with a polynomial on every subinterval of the whole interval on which is defined. In other words, splines are functions which are piecewise polynomial. The coefficients of the polynomial differs from interval to interval, but the order of the polynomial is the same.


1 Answers

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)))
like image 50
kohske Avatar answered Oct 04 '22 13:10

kohske