# Different colors for lines as opposed to points in R

I have a dataset of Cartesian coordinates. I want to make a basic scatter plot where each point is colored according to a pre-set vector of colors. This is easy to achieve with something like the following example.

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

However, if I want to draw a line between the points using type="o" or type="b" (depending on the system), the color of that line will default to the first color in the `Colors` vector.

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

What if I want the line to be a completely different color, e.g. black? In other words, how can I set the color of the line connecting the points to be independent of the coloring scheme of the points.

I am specifically looking for a solution to this problem in base (no ggplot), and ideally one that does not ask me to plot the lines and points in two separate steps (though if that's the only way, that's okay).

## 评论

### I think the correct way to d

I think the correct way to do this is actually to do it in two steps:

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

### The lines() function unfortu

The lines() function unfortunately does not seem to respect a multielement vector of colors for the `col` argument. Fortunately, segments() does, so you can do something like this:

``````## 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);
``````

### # A hypothetical dataset df

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