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.
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:
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")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With