Ahdee
Ahdee

Reputation: 4949

How to autogenerate color vector from a numeric vector

I have a numeric vector as such,

> z <- c("cat","cat","dog","dolphin","cat")
> z <- as.numeric( as.factor(z))
> z
[1] 1 1 2 3 1

from this, how do I autogenerate some color pallette? for example, c("red","red", "blue", "green", "red") or whatever color pallete is available.

I tried using rainbow(length(z)) but that did not work.

Upvotes: 1

Views: 872

Answers (1)

G5W
G5W

Reputation: 37641

I think that what you are intending is that if the values in z are the same, then the colors are the same. What you want is:

z <- c("cat","cat","dog","dolphin","cat")
rainbow(length(unique(z)))[as.numeric( as.factor(z))]
[1] "#FF0000FF" "#FF0000FF" "#00FF00FF" "#0000FFFF" "#FF0000FF"

This generates a different color for each distinct value of z, but when the values are equal, they get the same color.

Upvotes: 3

Related Questions