使用ggplot2绘制受限制的三次样条曲线的错误

时间:2016-01-12 20:00:39

标签: r ggplot2 splines

我想使用ggplot2来使用geom_smooth()使用受限制的三次样条曲线来说明拟合,但它似乎工作不正确。这是一个简短的例子:

# 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")

这会产生以下图像: Comparison of Splines 我不确定为什么geom_smooth()没有给出正确的结果。显然有一种解决方法(如上所示),但有没有办法让geom_smooth()产生正确的结果?

1 个答案:

答案 0 :(得分:2)

我不知道如何将其与geom_smooth集成,但我可以使用rms包中的ggplot.Predict进行此操作:

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

相关问题