如果我有一组数据,并绘制它,例如:
data=rnorm(100,1,2)
x=1:100
plot(x,data,type="l")
Run Code Online (Sandbox Code Playgroud)
如何将某些点更改为不同的颜色?如:
coloured=c(2,3,4,5,43,24,25,56,78,80)
Run Code Online (Sandbox Code Playgroud)
我想要coloured点,红色,如果可能的话,2,3,4和5之间的线为红色,因为它们是连续的.
像这样的东西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')
Run Code Online (Sandbox Code Playgroud)
输出:
正如@LyzandeR所提到的,你可以用你的情节绘制红点points.
points(coloured, data[coloured], col="red", pch=19)
Run Code Online (Sandbox Code Playgroud)
如果你想让红线少一些手动,你可以检查连续红点的位置,并将所有位线之间的红色(即点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")
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
158 次 |
| 最近记录: |