Change the color of some plot points

If I have a dataset and I draw it, for example:

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

How to change some dots to a different color? For example:

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

I would like the coloureddots in the word red and, if possible, the lines between 2,3,4 and 5 are red because they are consecutive.

+4
source share
2 answers

Something like this with pointsand linesmight 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

+6
source

As pointed out by @LyzandeR, you can draw red dots on your chart with points.

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

, , , ( 2, 3, 4, 5, 24 25 ):

# 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

+5

Source: https://habr.com/ru/post/1619045/


All Articles