在 R 中的 ggplot2 中外推散点图的线性拟合

Extrapolate linear fit for scatterplot in ggplot2 in R

我想对 ggplot2 中超出该数据区域的数据子集的数据进行线性拟合外推(以可视化外推的危险)。在下面的代码中,我想将 1980-1990 帧生成的线性拟合扩展到 1990-2000 年,这样我就可以添加整个时间段的完全拟合并可视化差异:

set.seed(123)           
frame <- data.frame(year = rep(1980:2000, 10), y = sample(1:1000, 210))
head(frame)

frame1 <- frame[frame$year %in% c(1980:1990),]
frame2 <- frame[frame$year %in% c(1980:2000),]

ggplot(frame1, aes(x = year, y = y)) + geom_point(shape = 1) + geom_smooth(method = lm) + xlim(1980, 2000)
ggplot(frame2, aes(x = year, y = y)) + geom_point(shape = 1) + geom_smooth(method = lm) + xlim(1980, 2000)

我是 ggplot2 的新手,所以任何关于如何从第一帧扩展线性拟合,然后添加数据和具有不同颜色的新拟合的任何想法都会很棒。谢谢

你可以试试

ggplot(frame2, aes(x = year, y = y)) + 
  geom_point(shape = 1) + 
  geom_smooth(method = lm, se=FALSE) + 
  geom_smooth(data=frame1, method = lm, fullrange=TRUE, se=FALSE, colour="red") + 
  xlim(1980, 2000)