[英]Errors Plotting a Restricted Cubic Spline with ggplot2
我想使用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")
這導致下圖:樣條曲線比較我不確定為什么geom_smooth()
沒有給出正確的結果。 顯然有一個解決方法(如上圖所示),但是有沒有辦法讓geom_smooth()
產生正確的結果?
已經很長時間了,但我終於認識到了這個問題,我想我會把它貼在這里供有興趣的人使用。 在內部, geom_smooth()
將創建一個預測器序列,其中預測響應為 plot。 由於此序列在 x 軸范圍內間隔開,因此geom_smooth()
rcs()
選擇的結點將不同於rcs()
在原始數據上選擇的結點。 要解決這個問題,您需要傳入正確的結點。
# 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, quantile(plot.dat$dist, probs = c(0.05, 0.275, 0.5, 0.725, 0.95))), se=FALSE, colour="blue") +
geom_line(aes(y=fitted, x=dist), colour="red")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.