如何绘制原始数据但在 ggplot2 R 中使用预测值进行线拟合?

How to plot raw data but use predicted values for line fit in ggplot2 R?

我有一个数据集 (dat),包含原始数据(raw_x 和 raw_y)。我已经预测了一个模型,模型的预测存储在 dat$predict 中。 我希望绘制原始数据,但用 geom_smooth (这里是二次函数)覆盖数据,但使用预测数据。这是我对基本代码的尝试。我还不确定如何在 geom_smooth 中使用预测值。

ggplot(dat, aes(x = raw_x, y = raw_y, colours = "red")) + 
  geom_point() +  
  theme_bw() + 
  geom_smooth(method = "lm", formula = y ~ x + I(x^2))

下图绘制了原始点、线性拟合线和拟合点。自从您发布 none.

以来,我使用了编造的数据
set.seed(1234)
x <- cumsum(rnorm(100))
y <- x + x^2 + rnorm(100, sd = 50)

dat <- data.frame(raw_x = x, raw_y = y)

fit <- lm(y ~ x + I(x^2), dat)
dat$predict <- predict(fit)

ggplot(dat, aes(x = raw_x, y = raw_y)) + 
  geom_point(colour = "blue") +  
  theme_bw() + 
  geom_smooth(method = "lm", formula = y ~ x + I(x^2), colour = "red") +
  geom_point(aes(y = predict), colour = "black")