我正在尝试使用predict()
填充值(行包含x值和y值作为NaN
)来填充包含数据的绘图中的预测曲线。这个想法是要获得比仅使用数据x值更平滑的预测曲线。但是,predict()
返回的时髦值似乎并不是基于y
值的x
计算。问题是:
这里是产生可怕结果的代码:
library(ggplot2)
library(nlme)
# generate test data frame
x = c(0, 5, 100, 1000, 50, 200, 300, 500)
y = c(0, 3, 5, 6, NaN, NaN, NaN, NaN)
df=data.frame(x,y)
# a log model to fit the data
lF <- formula(y ~ Ymax-(Ymax-Y0)*exp(-k*x))
# nonlinear regression
model <- nls(lF, data=df,
start=list(Ymax=3.0, k=0.01, Y0=0.3),
na.action = na.omit)
# print out the model resutls
summary(model)
# Derive predicted lines
df$pred <- predict(model)
# plot the data and three models
ggplot(df, aes(x=x, y=y))+
geom_point() +
geom_line(aes(y=pred))
如果您在newdata=df
命令中指定参数prediction
,则会得到:
# print out the model resutls
summary(model)
df$pred <- predict(model, newdata=df)
# plot the data and three models
ggplot(df, aes(x=x, y=y))+
geom_point(color="red", size=3) +
geom_line(aes(y=pred), size=1) +
theme_bw()
如果要从模型中绘制一条平滑线,则需要定义合适的x
值序列:
df2 <- data.frame(x=c(seq(0,1,0.001),1:1000))
df2$pred <- predict(model, newdata=df2)
ggplot(df, aes(x=x, y=y))+
geom_point(color="red", size=3) +
geom_line(data=df2, aes(x=x, y=pred), color="blue", size=1) +
theme_bw()