R 使用ggplot2绘制受限三次样条曲线时出错
我想使用R 使用ggplot2绘制受限三次样条曲线时出错,r,ggplot2,splines,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
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")
#rms包包含受限三次样条曲线(RCS)
图书馆(rms)
图书馆(GG2)
#加载数据
数据(汽车)
#RCS模型拟合
拟合我不知道如何将其与geom_smooth
集成,但我可以使用ggplot进行。从rms软件包中预测
:
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))
d我想知道这是否容易?rcs
-功能是“rms”世界的一部分。与“ggplot2”世界函数的情况一样,“rms”函数期望环境中有其他辅助函数和结构可用。ols
函数有单独的Predict
方法,类似于lm
。这需要指定datadist对象作为选项。当我运行Predict(ols(speed~rcs(dist,5),data=cars))
时,我得到的结果与您安装的相同。当我试图提供“ols”作为geom_smooth
的一种方法时,我得到了一个错误。我没有意识到有一个ggplot。预测函数:一个未回答的问题,建立了一个示例: