2

How to create a vector of colors where one certain output receives a different color than the others?

Manually it can be done like in the following example:

pts.7 <- cbind(1:7, 1:7)
mycols <- c("black","black","black","red","black","black","black")
plot(pts.7, col=mycols)

However for bigger data set like the following it doesn't work:

pts.400 <- cbind(runif(400), runif(400))
df <- data.frame(a = 1:400)
pts.400.df <- SpatialPointsDataFrame(pts.400, df)

How could a vector of colors be build that all points plotted get a grayscale color except point$a==158 which should be plotted red?

jay.sf
  • 60,139
  • 8
  • 53
  • 110
N'ya
  • 347
  • 3
  • 13
  • Possible duplicate of [ggplot2 : Color One Category Separately](https://stackoverflow.com/questions/39521580/ggplot2-color-one-category-separately) – A. Suliman Jul 13 '18 at 11:38
  • 2
    You can also do it manually using `mycols <- rep("black", 400); mycols[158] <- "red"` – nghauran Jul 13 '18 at 11:43
  • @A.Suliman, no this is not a ggplot question. – Axeman Jul 13 '18 at 11:45
  • @Axeman you are correct but it's a color related question. Also [here](https://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette) there is an answer to `ggplot2` and `base R`. – A. Suliman Jul 13 '18 at 11:47

1 Answers1

1

A trick is to use logical indexing:

plot(pts.400.df, col = c('black', 'red')[(pts.400.df$a == 158) + 1])

Each FALSE will be black, each TRUE will be red.

Axeman
  • 32,068
  • 8
  • 81
  • 94