I am working on a time series data analysis, for which I created a plot. In addition to showing the data points, I want to display a trend line. For this, the pre-intervention trend is supposed to be a solid line, whereas the "counterfactual scenario" (post-intervention trend line) is supposed to be dashed. So what I need is a line that is solid until 2005 and dashed from then on.
So far, I just managed to create a continuously solid line. This is what my plot looks like so far (I'm afraid I don't know how to use syntax hihlighting):
Q=ts(c(7.5,6.9,6.2,6.4,7.4,7.2,6.9,6.5,8.1,12.3,10.6,11.7,12.2,13.07,12.48,14.54,15.06,15.1,13.46,13.1,13.75,11.81,13.33,15.75), start = 1995, end =2018, frequency = 1)
tQ<-c(1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018)
plot(Q,type = "n", main = "Numbers per Year", xlab = "Year", ylab = "Q Number", ylim = c(0,35), xaxt='n')
rect(2005,-1,2018.5,36,col=grey(0.9),border=F) #post-intervention period
points(AR)
axis(side=1,at=c(1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018) , las = 2)
abline(v = 2005, lty = 2)
text(Q, labels = Q, cex = 0.7, pos = 3, offset = 1)
abline(lm(Q~tQ))
So far I haven't found any unseful information how to change the trendline.
Thank you very much for your help!
I am not so sure if this is what you are looking for but. Those codes give a dashed line after 2005. You just need to cancel out the very last abline()
in your codes and add those lines below,
#abline(lm(Q~tQ))
x <- tQ[11:length(tQ)]
y <- Q[11:length(Q)]
lines(x,fitted(lm(y~x)),col="blue",lty = 2)
Or, if you want to add a trend line starts to be dashed until 2005,
#abline(lm(Q~tQ))
fit <- lm(Q~tQ)
lines(tQ[1:11],fitted(fit)[1:11],col="blue")
lines(tQ[11:length(tQ)],fitted(fit)[11:length(tQ)],col="blue",lty = 2)
And lastly, if you desire to get a separated trend lines by before and after 2005,
#abline(lm(Q~tQ))
x1 <- tQ[1:11]
y1 <- Q[1:11]
x2 <- tQ[11:length(tQ)]
y2 <- Q[11:length(Q)]
lines(x1,fitted(lm(y1~x1)),col="blue")
lines(x2,fitted(lm(y2~x2)),col="blue",lty = 2)