how to use spline() with ggplot?

3,264 views
Skip to first unread message

David L

unread,
Nov 29, 2010, 5:38:56 PM11/29/10
to ggplot2
Hi,

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=_).
Is there a simple way to use spline() in ggplot other than fitting a
line through (spline(y~x)$x, spline(y~x)$y)?

Thanks,

David

Dennis Murphy

unread,
Nov 29, 2010, 10:04:34 PM11/29/10
to David L, ggplot2
Hi:

Here's an example:

x = seq(0, 2 * pi, length = 500)
df <- data.frame(x = x, y = sin(x) + rnorm(500, s = 0.3))

library(splines)
ggplot(df, aes(x = x, y = y)) + geom_point() +
     stat_smooth(data = g, aes(x = x, y = y), method = 'lm',
                          formula = y ~ ns(x, 3), col = 'red', size = 2, se= FALSE)

It should be simpler if you use lm() with one of the spline functions generating the basis matrix. I used ns() here, but one could use other basis functions equally well. Here's a different example using the rcs() function in package rms:

library(rms)
ggplot(df, aes(x = x, y = y)) + geom_point() +
     stat_smooth(data = g, aes(x = x, y = y), method = 'lm',
                          formula = y ~ rcs(x, 4), col = 'red', size = 2, se= FALSE)

The graph should be essentially the same. The se argument is unneeded because confidence curves won't be plotted if you specify se = TRUE.

HTH,
Dennis


--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: http://gist.github.com/270442

To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

David L

unread,
Dec 21, 2010, 5:12:44 PM12/21/10
to ggplot2
Hi Dennis,

Thank you for your help, but these approaches uses a smoothed spline
and I would like to fit a spline through all of the points.

In addition, I am using the spline() function for my analysis so it
would definitely be preferable to use spline() instead of rcs() or
ns().

Do you know how I can incorporate spline() into ggplot?

Thanks,

David
> > To unsubscribe: email ggplot2+u...@googlegroups.com<ggplot2%2Bunsu...@googlegroups.com >
> > More options:http://groups.google.com/group/ggplot2

Dennis Murphy

unread,
Dec 22, 2010, 10:24:10 AM12/22/10
to David L, ggplot2
From the help page of spline():

spline returns a list containing components x and y which give the ordinates where interpolation took place and the interpolated values.

Take the results from spline(), assign them to an object, convert it to a data frame and use that as input into ggplot(), where you can use either geom_path() or geom_line() to produce the plot.

HTH,
Dennis


Reply all
Reply to author
Forward
0 new messages