Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors Plotting a Restricted Cubic Spline with ggplot2

Tags:

r

ggplot2

splines

I would like to use ggplot2 to illustrate a fit using a restricted cubic spline using geom_smooth() but it seems to be working incorrectly. Here is a short example:

# rms package Contains Restricted Cubic Splines (RCS)
library(rms)
library(ggplot2)

# Load Data
data(cars)

# Model Fit with RCS
fit <- lm(speed ~ rcs(dist, 5), data=cars)

# Obtain Diagnostic Data
plot.dat <- cbind(cars, fitted=fitted(fit))

# Compare Smooth to Actual
ggplot(data=plot.dat) +
  geom_point(aes(x=dist, y=speed)) +
  geom_smooth(aes(x=dist, y=speed), method="lm", 
              formula=y ~ rcs(x, 5), se=FALSE, colour="blue") +
  geom_line(aes(y=fitted, x=dist), size=1.25, colour="red")

This results in the following image: Comparison of Splines I am not sure why geom_smooth() is not giving the correct results. Clearly there is a work-around (as illustrated above), but is there a way to make geom_smooth() produce the correct results?

like image 454
reyesem Avatar asked Sep 26 '26 00:09

reyesem


1 Answers

I don't know how to integrate this with geom_smooth but I can do it with ggplot.Predict from the rms package:

ddist <- datadist(cars)
options(datadist='ddist')

fit <- ols(speed~  rcs(dist,5),data=cars,
               x=TRUE, y=TRUE)

ggplot(Predict(fit))+geom_point(data=cars, aes(x=dist, y=speed))

enter image description here

like image 104
IRTFM Avatar answered Sep 28 '26 17:09

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!