0

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 0s and 1932 1s 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?

  • 1
    this? `df <- data.frame(x=1:10, y=11:20, z=rep(c(1,3),5)); plot(df[,1:2],type="n"); for(i in 1:nrow(df)){ lines(df[i:(i+1),1], df[i:(i+1),2], col=df[i,3])}` – Roman Jan 17 '18 at 13:28
  • Mhh, not quite. I stored the three vectors in a data frame and assigned the third column the characters "black" and "green", respectively. The for loop works the way you wrote it but not when I use `[i, 1]` instead of `[i:(i+1), 1]` (for each column respectively) which is what I actually want. There is no error message, it's just that nothing is plotted when executing the code. – Arne Brandschwede Jan 17 '18 at 15:22
  • When using this `[i, 1]` you have to change `lines` into `points`. `lines` need start and end point. – Roman Jan 17 '18 at 15:26
  • Makes sense. Works when changed to `points()`. I would still rather have lines visualised but that should be possible somehow with the correct graphical parameters inside `points()`. Any thoughts on why it did not work with the code I had in the first place (the one in the original post)? Why the detour with creating a data frame first? – Arne Brandschwede Jan 17 '18 at 16:13

0 Answers0