rubengura
rubengura

Reputation: 469

Drawing a line on time series plot

I have the next time series object, which I plot it using plot:

ts <- ts(c(1:4,2:5,3:6,4:7,5:8,6:9,7:10), frequency = 4)
plot(ts)

Plot of the ts

Now, I would like to draw a line between the first and the last observation using abline, but, although R doesn't show any error, it seems that it doesn't work when using it on a plot of time series. The code used to try to draw the line was:

abline(a = 1, b = (ts[length(ts)]- ts[1]) / (length(ts)-1))

Did anyone had the same problem and manage to solve it?

enter image description here

Upvotes: 0

Views: 1570

Answers (2)

Marco Sandri
Marco Sandri

Reputation: 24252

ts <- ts(c(1:4,2:5,3:6,4:7,5:8,6:9,7:10), frequency = 4)
plot(ts, xlim=c(1,8), type="o")

x1 <- 1; y1 <- ts[1]
x2<- 7.75; y2 <- ts[length(ts)]

abline(a = y1-x1*(y1-y2)/(x1-x2), b = (y1-y2)/(x1-x2) )
grid()

enter image description here

Upvotes: 1

KoenV
KoenV

Reputation: 4283

I am not sure that I fully understand what you want to achieve. But the following may be of help.

You may use the following simple code using lines:

# your code
ts <- ts(c(1:4,2:5,3:6,4:7,5:8,6:9,7:10), frequency = 4)
plot(ts)

# drawing a blue line from (1, 1) to (8, 10)
lines(x = c(1, 8), y = c(1,10), col="blue")

which yields the following simple plot

enter image description here

Upvotes: 0

Related Questions