Is there a straight-forward way to add a smooth.spline() layer to a
scatter plot? I expected to find such a method in stat_smooth() but I
couldn't find it in the bestiary of lm, glm, loess, etc.
x = seq(1,10, length=100)
y = jitter(sin(x), a = 0.4)
qplot(x, y, data=data.frame(x,y), geom="point") +
geom_smooth()
# compare with
dev.new()
plot(x,y)
sp = smooth.spline(x,y)
lines(sp)
Best regards,
baptiste
The easiest way to use smooth.spline with geom_smooth would be to
write a wrapper for it that implemented the usual formula based
interface. This would be a couple of lines, possibly using
model.matrix to generate the x values.
Hadley
> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> To post to this group, send email to ggp...@googlegroups.com
> To unsubscribe from this group, send email to
> ggplot2+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/ggplot2
--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/
Thanks, that makes sense, but I must admit I have no clue how to do
it. I'm not at all familiar with model.frame, formula, model.matrix,
etc. and their help pages haven't enlightened me a bit.
I guess the idea is the following,
smoothing <- function(formula, data, ...){
## associate x and y to the data from the formula
## ...
sp <- smooth.spline(x, y, ...)
## recast the output
}
and then use,
geom_smooth( method = "smoothing" )
but I don't know how to use the formula and the data to extract x and
y, nor how to format the output to please stat_smooth. It's not big
deal though, I can always create the data myself with smooth.spline
and plot it.
Thanks,
baptiste
Here's the minimal code you need to get up and running:
smooth.spline2 <- function(formula, data, ...) {
mat <- model.frame(formula, data)
smooth.spline(mat[, 2], mat[, 1])
}
predictdf.smooth.spline <- function(model, xseq, se, level) {
pred <- predict(model, xseq)
data.frame(x = xseq, y = pred$y)
}
qplot(mpg, wt, data = mtcars) + geom_smooth(method = "smooth.spline2", se= F)
Hadley
baptiste