Hao
Hao

Reputation: 59

plot vertical color line in R

I would like to plot multiple color vertical line for a time series as below,

    [1,] 4.698478   0
    [2,] 4.698205   1
    [3,] 4.698569   0
    [4,] 4.697385   -1
    ...

to plot a blue color vertical line when [,2] is 1, and a red line when [,2] is -1, wonder if someone can help, thanks!

Upvotes: 0

Views: 1608

Answers (3)

Hao
Hao

Reputation: 59

I ended up using quantmod's charting function, pretty good results.

chartSeries(price[,1])
addTA(price[,2]==1,pch=1, on=1,col="blue")
addTA(price[,2]==-1,pch=1, on=1,col="red")

Upvotes: 0

Matthew Plourde
Matthew Plourde

Reputation: 44614

Nothing wrong with @ChristopherLouden's answer, but this would be a way to do it in a single call to abline:

abline(v=m[,1], col=c('red', NA, 'blue')[as.numeric(as.factor(m[,2]))])

Upvotes: 0

Christopher Louden
Christopher Louden

Reputation: 7592

You can do the following, assuming data[, 1] is the x-value for the vertical line:

abline(v = data[data[, 2] == 1, 1], col = 'blue')
abline(v = data[data[, 2] == -1, 1], col = 'red')

Upvotes: 1

Related Questions