【发布时间】:2016-03-13 12:17:32
【问题描述】:
如果我有一组数据,并绘制它,例如:
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 之间的线为红色,因为它们是连续的。
【问题讨论】:
如果我有一组数据,并绘制它,例如:
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 之间的线为红色,因为它们是连续的。
【问题讨论】:
正如@LyzanderR 提到的,您可以使用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")
})
【讨论】: