我试图用ggplot绘制一个时间序列中的多条趋势线(每十年一次)。
数据如下:
dat <- structure(list(YY = 1961:2010, a = c(98L, 76L, 83L, 89L, 120L,
107L, 83L, 83L, 92L, 104L, 98L, 91L, 81L, 69L, 86L, 76L, 85L,
86L, 70L, 81L, 77L, 89L, 60L, 80L, 94L, 66L, 77L, 85L, 77L, 80L,
79L, 79L, 65L, 70L, 80L, 87L, 84L, 67L, 106L, 129L, 95L, 79L,
67L, 105L, 118L, 85L, 86L, 103L, 97L, 106L)), .Names = c("YY",
"a"), row.names = c(NA, -50L), class = "data.frame")
剧本如下:
p <- ggplot(dat, aes(x = YY))
p <- p + geom_line(aes(y=a),colour="blue",lwd=1)
p <- p + geom_point(aes(y=a),colour="blue",size=2)
p <- p + theme(panel.background=element_rect(fill="white"),
plot.margin = unit(c(0.5,0.5,0.5,0.5),"cm"),
panel.border=element_rect(colour="black",fill=NA,size=1),
axis.line.x=element_line(colour="black"),
axis.line.y=element_line(colour="black"),
axis.text=element_text(size=15,colour="black",family="serif"),
axis.title=element_text(size=15,colour="black",family="serif"),
legend.position = "top")
p <- p + scale_x_discrete(limits = c(seq(1961,2010,5)),expand=c(0,0))
p <- p + geom_smooth(data=dat[1:10,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")
p <- p + geom_smooth(data=dat[11:20,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")
p <- p + geom_smooth(data=dat[21:30,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")
p <- p + geom_smooth(data=dat[31:40,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")
p <- p + geom_smooth(data=dat[41:50,],aes(x=YY,y=a),method="lm",se=FALSE,color="black",formula=y~x,linetype="dashed")
p <- p + labs(x="Year",y="Number of Days")
outImg <- paste0("test",".png")
ggsave(outImg,p,width=8,height=5)
这是生成的图像:
我想要的/问题
-
我想提取斜率并将其添加到图中的趋势线上。如何从geom_smooth()中提取每条线的坡度?
-
目前,我正在逐一绘制趋势线。我想知道是否有一个有效的方法来做这个与可调的时间窗口。例如,我想每5年绘制一次趋势线。在上图中,时间窗口是10。
-
假设,我只想绘制有效的趋势线(即p-value<0.05,空:没有趋势或斜率等于0),是否可以用geom_smooth()实现?
我很感激你的帮助。