R - 在同一图上绘制2条趋势线并更改​​线长

时间:2014-08-23 21:50:11

标签: r plot trendline

我有一个包含实际值和建模值的数据集。我将数据集拆分为2003年1月 - 2006年12月和2007年1月 - 2012年12月两个时期并绘制了趋势线 - 实际值有两个趋势线(2个时间段),2个用于建模。我附上了一张照片 - 我想控制线条的长度,以便它们在正确的时间开始和停止 - 但我无法弄清楚这一点!我已附上我迄今为止管理的代码 - 我还是相当新的。如果以上内容不清楚,还附上了一张图片。谢谢!

我不确定我是否有办法在2007年(1月)放置一条垂直线并使用此线作为参考来启动和停止相应的线路?

plot(NULL, type="n", xlim=x.limit, ylim=c(-30, 30), xlab="Year", ylab="Equivalent Water     Depth (cm)", axes=F, cex.lab=0.9)

box(lwd=1.5)
abline(h=0, col="gray50", lty=1, lwd=1)
axis(1, seq(2003, 2013, 1), cex.axis=0.7)
axis(2, seq(-40, 40, 10), las=1, cex.axis=0.7, tck=-0.03)
minor.tick(nx=4, ny=0, tick.ratio=0.5)
lines(tws.avg.VNB[,2] ~ tws.avg.VNB[,1], type="l", lwd=2, col=1) 

tws.slope1 <- round(as.vector(coef(lm(SPLIT.1.ALL.VNB[,2] ~ SPLIT.1.ALL.VNB[,1]))[2]), 2)
tws.sdev1 <- round(as.vector(coef(summary(lm(SPLIT.1.ALL.VNB[,2] ~ SPLIT.1.ALL.VNB[,1])))[, "Std. Error"][2]), 2)
mtext(paste("GRACE Trend: 2003-2007 (cm/yr): ", tws.slope1, "±", tws.sdev1, sep=""), cex=0.5, side=1, line=-1.8, adj=0.15)
abline(lm(SPLIT.1.ALL.VNB[,2] ~ SPLIT.1.ALL.VNB[,1]), lwd=2, lty=2, col="deepskyblue")

tws.slope2 <- round(as.vector(coef(lm(SPLIT.2.ALL.VNB[,2] ~ SPLIT.2.ALL.VNB[,1]))[2]), 2)
tws.sdev2 <- round(as.vector(coef(summary(lm(SPLIT.2.ALL.VNB[,2] ~ SPLIT.2.ALL.VNB[,1])))[, "Std. Error"][2]), 2)
mtext(paste("GRACE Trend: 2007-2012 (cm/yr): ", tws.slope2, "±", tws.sdev2, sep=""), cex=0.5, side=1, line=-1.1, adj=0.15)
abline(lm(SPLIT.2.ALL.VNB[,2] ~ SPLIT.2.ALL.VNB[,1]), lwd=2, lty=2, col="deepskyblue")
lines(VNB.OBS.TWS[,1] ~ tws.avg.VNB[,1], type="l", lwd=2, col="red")

tws.slope3 <- round(as.vector(coef(lm(SPLIT.1.ALL.VNB[,6] ~ SPLIT.1.ALL.VNB[,1]))[2]), 2)
tws.sdev3 <- round(as.vector(coef(summary(lm(SPLIT.1.ALL.VNB[,6] ~ SPLIT.1.ALL.VNB[,1])))[, "Std. Error"][2]), 2)
mtext(paste("OBSERVED Trend: 2003-2007 (cm/yr): ", tws.slope3, "±", tws.sdev3, sep=""), cex=0.5, side=1, line=-1.8, adj=0.85)
abline(lm(SPLIT.1.ALL.VNB[,6] ~ SPLIT.1.ALL.VNB[,1]), lwd=2, lty=2, col="forestgreen")

tws.slope4 <- round(as.vector(coef(lm(SPLIT.2.ALL.VNB[,6] ~ SPLIT.2.ALL.VNB[,1]))[2]), 2)
tws.sdev4 <- round(as.vector(coef(summary(lm(SPLIT.2.ALL.VNB[,6] ~ SPLIT.2.ALL.VNB[,1])))[, "Std. Error"][2]), 2)
mtext(paste("OBSERVED Trend: 2007-2012 (cm/yr): ", tws.slope4, "±", tws.sdev4, sep=""), cex=0.5, side=1, line=-1.1, adj=0.85)
abline(lm(SPLIT.2.ALL.VNB[,6] ~ SPLIT.2.ALL.VNB[,1]), lwd=2, lty=2, col="forestgreen")

legend("bottomright", "(a)", bty="n", cex=0.8) 
legend("top", legend=expression(Delta~TWS~(GRACE), GRACE~TREND, Delta~TWS~(OBSERVED), OBSERVED~TREND),
   lty=c(1,4,1,4), lwd=c(2,2,2,2), col=c(1,"deepskyblue","red","forestgreen"),
   bty="n", horiz=T, cex=0.6)

The code is for the top plot!

1 个答案:

答案 0 :(得分:0)

查看包zoo。在许多其他功能中,它实现了一个专门用于跟踪时基的时间序列的新类,plot.zoo方法使用它。作为一个非常非常小的例子,您可以尝试以下内容:

a <- zoo(rnorm(5), 1:5)
b <- zoo(rpois(5, 1), 1:5)
plot(cbind(a, b))

基础R解决方案也非常简单:

a <- rnorm(5)
b <- rpois(5, 1)
plot(a ~ 1:5, xlim = c(0, 10))
points(b ~ 6:10)