I drew an empty plot and subsequently added a lines()
function that draws a time series of a numeric vector. I want to change the line so as the line colour (alternatively the line type) varies binary, depending on another numeric vector containing 0
and 1
. This is what I got so far:
lines(x, y, type = "l",
col = ifelse(z == 0, "black", "green"))
x
and y
are numeric vectors num [1:2718]
listing the points to join; x
just contains numerics from 1 to 2718. z
is the binary numeric vector num [1:2718]
that contains only 0
and 1
; there are 786 0
s and 1932 1
s in z
. For each case z == 0
, the line should be coloured black and in all other cases (z == 1
), the line should be green. All three vectors have the same length.
Problem: So far, the line is all green, likely because the first element of z
is 1. After I manually changed the first element from 1 to 0, the line was all black. It seems that R just takes the first element of z
and colours the line accordingly. Using z[i]
or z[x]
does not change anything, the line is still all green.
I cannot think of a way to tell R to fetch each element of z
successively and use the conditional colours accordingly while plotting along x
and y
. If it would be easier for any reason to use conditional line types than colours I am happy with such a solution as well. I am using base graphics.
Any ideas on that?