【问题标题】:Different colors for lines as opposed to points in R与 R 中的点不同,线的颜色不同
【发布时间】:2016-08-14 23:29:27
【问题描述】:

我有一个笛卡尔坐标数据集。我想制作一个基本的散点图,其中每个点都根据预设的颜色向量进行着色。这很容易通过以下示例实现。

# A hypothetical dataset
XCoords<-c(1,3,5,6,8)
YCoords<-c(3,9,4,3,4)

# Sorry for picking such ugly colors, its just an example
Colors<-c("#FDA75F","#F1E19D","#E5AC4D","#FDC07A","#FDB46C")

# Plot the scatter plot
plot(x=XCoords,y=YCoords,pch=16,col=Colors)

但是,如果我想使用 type="o" 或 type="b" (取决于系统)在点之间画一条线,那条线的颜色将默认为Colors 中的第一种颜色向量。

# An example using type="o"
plot(x=XCoords,y=YCoords,pch=16,col=Colors,type="o")

如果我希望线条是完全不同的颜色怎么办,例如黑色的?换句话说,如何将连接点的线的颜色设置为独立于点的着色方案。

我特意在base(没有ggplot)中寻找解决这个问题的方法,理想情况下,它不会要求我在两个单独的步骤中绘制线和点(尽管如果这是唯一的方法,那没关系)。

【问题讨论】:

    标签: r plot


    【解决方案1】:

    我认为正确的做法实际上是分两步进行:

    plot(x=XCoords,y=YCoords,pch=16,col=Colors)
    lines(x = XCoords,y=YCoords,col = "black")
    

    【讨论】:

    • 另外,plot(x=XCoords,y=YCoords,pch=16,col=Colors); par(new = TRUE); plot(x=XCoords,y=YCoords,col="black", type="l") 可能会起作用。
    • 我怀疑这就是答案。虽然我建议也许分三个步骤来做,用 plot(..., type="n") 然后是lines(),然后是 points()。这样这条线就不会出现在点的顶部。
    【解决方案2】:

    不幸的是,lines() 函数似乎不尊重 col 参数的多元素颜色向量。幸运的是,segments() 可以,所以你可以这样做:

    ## a hypothetical dataset
    x <- c(1,3,5,6,8);
    y <- c(3,9,4,3,4);
    
    ## separate point and line colors
    col.point <- c('red','green','blue','yellow','cyan');
    col.line <- c('magenta','black','grey','brown');
    
    ## scatter plot
    plot(x,y,pch=16L,col=col.point);
    ##lines(x,y,col=col.line); ## bad, would only use col.line[1L]
    segments(x[-length(x)],y[-length(y)],x[-1L],y[-1L],col=col.line);
    

    【讨论】:

    • 我实际上并没有考虑将颜色的多元素向量传递给线条,但这对了解很有帮助!
    【解决方案3】:
    # A hypothetical dataset
    df <- data.frame(
      x = rep(seq(2000, 2019, 1), 5),
      y = rnorm(100),
      id = rep(1:5, each = 20)
    )
    
    
    cols <- data.frame(
      col = palette.colors(length(unique(df$id))),
      id = unique(df$id)
    )
    
    # Plot 
    with(df, {
      plot(x, y, pch = 16, col = cols$col[match(id, cols$id)], type = "p")
      for (l in unique(id)) {
        lines(x[id == l], y[id == l], type = "l", col = cols$col[match(l, cols$id)])
      }
    }))
    

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      相关资源
      最近更新 更多