Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change colour of some points in plot

Tags:

plot

r

colors

If I have a set of data, and I plot it, for example:

data=rnorm(100,1,2)
x=1:100
plot(x,data,type="l")

How would I change certain points to a different colour? Such as:

coloured=c(2,3,4,5,43,24,25,56,78,80)

I would like the coloured points in say, red, and if possible, the line between 2,3,4 and 5 in red since they are consecutive.

like image 857
sym246 Avatar asked Dec 08 '15 14:12

sym246


2 Answers

Something like this with points and lines might be of help:

#your data
data=rnorm(100,1,2)
x=1:100
plot(x,data,type="l")
coloured=c(2,3,4,5,43,24,25,56,78,80)

#coloured points
points(coloured, data[coloured], col='red')

#coloured lines
lines(c(2,3,4,5), data[c(2,3,4,5)], col='red')

Output:

enter image description here

like image 66
LyzandeR Avatar answered Sep 27 '22 18:09

LyzandeR


As @LyzandeR mentionned, you can plot red points on your plot with points.

points(coloured, data[coloured], col="red", pch=19)

If you want to make the red lines a bit less manual, you can check where the consecutive red points are and put all bits of lines in between in red (that is, between points 2, 3, 4, 5 but also between points 24 and 25 in your example):

# get insight into the sequence/numbers of coloured values with rle
# rle on the diff values will tell you were the diff is 1 and how many there are "in a row"
cons_col <- rle(diff(coloured)) 
# get the indices of the consecutive values in cons_col
ind_cons <- which(cons_col$values==1)    
# get the numbers of consecutive values
nb_cons <- cons_col$lengths[cons_col$values==1]
# compute the cumulative lengths for the indices
cum_ind <- c(1, cumsum(cons_col$lengths)+1)

# now draw the lines:
sapply(seq(length(ind_cons)), 
       function(i) {
          ind1 <- cum_ind[ind_cons[i]]
          ind2 <- cum_ind[ind_cons[i]] + nb_cons[i]
          lines(coloured[ind1:ind2], data[coloured[ind1:ind2]], col="red")
       })

enter image description here

like image 23
Cath Avatar answered Sep 27 '22 17:09

Cath