如果我有一组数据,并且对其进行绘图,例如:
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)
我希望将有颜色
的点以红色显示,如果可能的话,将2、3、4和5之间的连线也标记为红色,因为它们是连续的。
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")
})