Question

How would one use the smooth.spline() method in a ggplot2 scatterplot?

If my data is in the data frame called data, with two columns, x and y.

The smooth.spline would be sm <- smooth.spline(data$x, data$y). I believe I should use geom_line(), with sm$x and sm$y as the xy coordinates. However, how would one plot a scatterplot and a lineplot on the same graph that are completely unrelated? I suspect it has something to do with the aes() but I am getting a little confused.

Was it helpful?

Solution

You can use different data(frames) in different geoms and call the relevant variables using aes or you could combine the relevant variables from the output of smooth.spline

# example data
set.seed(1)
dat <- data.frame(x = rnorm(20, 10,2))
dat$y <- dat$x^2 - 20*dat$x + rnorm(20,10,2)

# spline
s <- smooth.spline(dat)

# plot - combine the original x & y and the fitted values returned by 
# smooth.spline into a data.frame

library(ggplot2)

ggplot(data.frame(x=s$data$x, y=s$data$y, xfit=s$x, yfit=s$y)) +
                      geom_point(aes(x,y)) + geom_line(aes(xfit, yfit))

# or you could use geom_smooth    
ggplot(dat, aes(x , y)) + geom_point() + geom_smooth()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top