线条的不同颜色与R中的点相对

时间:2016-04-21 16:08:18

标签: r plot

我有一个笛卡尔坐标数据集。我想制作一个基本的散点图,其中每个点根据预先设定的颜色矢量着色。使用类似下面的示例很容易实现。

# 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 =&#34; o&#34;在点之间画一条线。或者输入=&#34; b&#34; (取决于系统),该行的颜色将默认为Colors向量中的第一种颜色。

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

如果我希望线条颜色完全不同,例如黑色?换句话说,如何设置连接点的线的颜色与点的着色方案无关。

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

3 个答案:

答案 0 :(得分:3)

遗憾的是,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);

plot

答案 1 :(得分:2)

我认为这样做的正确方法实际上是分两步完成:

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

答案 2 :(得分:0)

# 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)])
  }
}))

enter image description here

相关问题