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

cod*_*art 2 r ggplot2 lm extrapolation

我想对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)
Run Code Online (Sandbox Code Playgroud)

我是新手,ggplot2所以如何从第一帧扩展线性拟合,然后添加数据和新的拟合与不同的颜色将是伟大的.谢谢.

luk*_*keA 5

你可以试试

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) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述