I would like to color X-axis intervals of a plot line with different colours between these points:
52660, 106784, 151429, 192098, 233666, 273857, 307933, 343048, 373099, 408960, 441545, 472813, 497822, 518561, 537471, 556747, 571683, 591232, 599519, 616567, 625727, 633745
The intervals represent SNP positions along 22 chromosomes.
The problem is that the intervals are unequal (e.g. 52660 - 106784, 106784 - 151429, ... 472813 - 497822, ...). Y-axis values represent ancestry frequencies. X-axis name is SNP_position
The closest I have found is using "ifelse", but for some reason it doesn't work well for me.
For instance, for the first interval (0 - 52660) I included the "col" variable for "plot" and I tried:
col = ifelse(SNP_position < 52660,'blue', 'green')
or
col=ifelse(SNP_position < 52660 & SNP_position > 106784,"blue","green")
but when I do this the whole line becomes green.
Here is the plot I want to colour
Any help would be highly appreciated.
Here's a proof of concept on how to do it with segments
. First step is to create a vector of alternating segments. I'm using even and odds to do this. You will have to plug in the correct y-axis data in your code.
x <-1:700000
segments <-c(52660, 106784, 151429, 192098, 233666, 273857, 307933, 343048, 373099, 408960, 441545, 472813, 497822, 518561, 537471, 556747, 571683, 591232, 599519, 616567, 625727, 633745)
stOdds <- segments[1:length(segments) %% 2 == 1]
stEvens <- segments[1:length(segments) %% 2 == 0]
plot(x, type="l", col="green", lwd=2)
segments(stOdds,stOdds,stEvens,stEvens,col="blue", lwd=2)
UPDATE
With the additional info, here's how to do it with cut
, and lines
.
#create data
x <-1:700*1000
y <-runif(700)
z <-data.frame(x,y)
#cut in segments
my_segments <-c(52660, 106784, 151429, 192098, 233666, 273857, 307933, 343048, 373099, 408960, 441545, 472813, 497822, 518561, 537471, 556747, 571683, 591232, 599519, 616567, 625727, 633745)
my_cuts <-cut(x,my_segments, labels = FALSE)
my_cuts[is.na(my_cuts)] <-0
#create subset of of segments
z_alt <-z
z_alt[my_cuts %% 2 == 0,] <-NA
#plot green, then alternating segments in blue
plot(z, type="l", col="green", lwd=2)
lines(z_alt,col="blue", lwd=2)