如果我有一组数据,我会绘制它,例如:
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
点,红色,如果可能的话,2,3,4和5之间的线为红色,因为它们是连续的。
答案 0 :(得分:6)
points
和lines
之类的内容可能会有所帮助:
#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')
输出:
答案 1 :(得分:5)
正如@LyzandeR所提到的,你可以使用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")
})