0
votes

I have very specific ranges I would like to plot in different colors on the same plot using the plot function in R.

The ranges are in a matrix that looks like this:

x
     [,1] [,2]
[1,]    0  600
[2,]  700  900
[3,]  950 1000
[4,] 1200 1400

I have a data frame that looks like this:

head(df)
  V1   V2  V3 V4 V5 V6
1  0 -280 -93  3  x x        
2  1 -279 -93  2  y y        
3  2 -278 -93  1  z z        

I would like plot column V2 and I would like 5 different colors in the plot: 1 color for position df$V2 0-600, 1 color for 700-900, 1 color for 950-1000, and one color for 1200-1400, and another color for everything else that is not in those ranges (black for example).

I have other matrices that have different sizes, so ideally the code can be used for different amounts of ranges.

2
Are you plotting points? lines? What's the x and what's the y in the plot? Three rows isn't a super helpful dataset to test with given that zero points line in any of the specified boundaries.MrFlick
Your ranges aren't closed. What do you want when, e.g., V2 is between 600 and 700, or between 900 and 950??jlhoward
I am plotting lines using plot(df$V2, type='l'). The x-axis is just an index. The column I'm printing has values that range from -300 to +2000user3141121
if V2 is between 600 and 700 I want that segment of the plot to be a different coloruser3141121

2 Answers

1
votes

Something like this?

x1 <- matrix(c(0, 600, 700, 900, 950, 1000, 1200, 1400),
             nrow=4, ncol=2, byrow=TRUE)
y1 <- seq(-300, 2000)
plot(y1, y1, lwd=1)
for (i in 1:nrow(x1)){
    y2 <- y1[y1 >= x1[i, 1] & y1 <= x1[i, 2]]
    lines(y2, y2, col=i+1, lwd=10)
}

giving

enter image description here

0
votes

Just for the sake of having several solutions at hand:

x1 <- matrix(c(0, 600, 700, 900, 950, 1000, 1200, 1400),
             nrow=4, ncol=2, byrow=TRUE)
y1 <- seq(-300, 2000)
a <- sapply(y1,function(i)i>=x1[,1]&i<=x1[,2])
col <- apply(a,2,function(x)ifelse(any(x),which(x),0)) #Pick which group each element belongs to, if none assigns "0".
plot(y1,col=col+1)

enter image description here