【问题标题】:Change colour of some points in plot更改绘图中某些点的颜色
【发布时间】: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 之间的线为红色,因为它们是连续的。

【问题讨论】:

    标签: r plot colors


    【解决方案1】:

    pointslines 这样的东西可能会有所帮助:

    #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')
    

    输出:

    【讨论】:

      【解决方案2】:

      正如@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")
             })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-11-30
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 2012-05-01
        • 1970-01-01
        • 2020-02-09
        相关资源
        最近更新 更多