我想将一个简单的三次多项式拟合到数据,然后构建具有三种不同几何形状的图形:我在其上拟合模型的一组数据点(蓝色的geom_point
,这些点+预测间隔(geom_line
,也为蓝色)和对模型适用的天数的预测(geom_line
,为红色)。这是我的代码:
library(ggplot2)
positives <- c(13, 65, 118, 229, 322, 455, 655, 888, 1128, 1577)
days_passed <- length(positives)
t <- seq(1, days_passed)
t_full <- c(t, seq(t[days_passed], 30))
model <- lm(positives ~ poly(t,degree=3))
predict_positives <- predict(model, list(t = t_full), interval = "prediction")
# plot
length(positives) <- length(t_full)
dframe <- data.frame(day = t_full,
positives = positives,
future = ifelse(t_full <= days_passed, "N", "Y"),
lwr = predict_positives[, "lwr"],
fit = predict_positives[, "fit"],
upr = predict_positives[, "upr"])
p <- ggplot(dframe, aes(x = day, y = positives, color = future)) +
geom_point() +
geom_line(aes(y = fit)) +
geom_line(aes(y = lwr), linetype = "dashed") +
geom_line(aes(y = upr), linetype = "dashed") +
geom_vline(xintercept = 17, linetype = "dashed") +
geom_vline(xintercept = 24)
print(p)
但是,结果图显示出不美观的间隙:
如何修改我的代码,以使拟合和预测是连续的?
答案 0 :(得分:2)
您的future
列的第10天对应的两行的值均为N
。如果您仅更改此值,则图将显示您的预期。
dframe$future[11] <- "Y"
ggplot(dframe, aes(x = day, y = positives, color = future)) +
geom_point() +
geom_line(aes(y = fit)) +
geom_line(aes(y = lwr), linetype = "dashed") +
geom_line(aes(y = upr), linetype = "dashed") +
geom_vline(xintercept = 17, linetype = "dashed") +
geom_vline(xintercept = 24)