Wrong matches between colors and values when defining colorFactor

43 Views Asked by At

In my R code I have a dataset where column "Groups" shows which observations belong to different groups. I would like to assign a unique color to each group. For example, I can then use these colors in a leaflet map. However, there is problem which I do not understand: when creating the colorFactor, some values get wrong colors.

Here is an example. I define colors in the top (I have more colors than I will need in this specific dataset, but the idea is that once the size of the dataset is known, the same number of different colors is taken). Then I create a dataset (where a problem arises) and add a column with the associated colors. Some of the colors turn out to be wrong, and I would like to understand why.


#Define distinct colors (first one is NA color)
MyColors = c("#808080","red", "green", "yellow", "orange", "violet", "palegreen4","wheat2","mediumpurple1", "turquoise2", "steelblue", "yellowgreen","tan3","tomato", 
             "palevioletred", "maroon1", "springgreen2" , "brown","violetred","coral2")

#Create a dataset where the problem arises
MyTest=c(NA,NA,"Group94",NA,NA,"Group193", NA, "Group275", NA, NA, NA, "Group381", NA, "Group435", NA, "Group475", "Group507", NA, "Group193", "Group558", "Group572", "Group94", "Group572","Group650","Group475","Group558","Group684",NA, "Group381", NA, "Group715","Group435","Group715",NA,"Group507","Group684","Group275","Group650")
MyTest=as.data.frame(MyTest)
colnames(MyTest)="Groups"

#Define the colors:
MyDomainColors=MyTest %>% select(Groups) %>% distinct() %>% arrange()
MyDomainColors=as.vector(MyDomainColors[,1])
MyPal <- colorFactor(MyCol[1:length(MyDomainColors)], domain = MyDomainColors, ordered = TRUE)

#Add color as a separate column
MyTest=MyTest %>% mutate(MyColor=MyPal(MyTest$Groups))

Here I have 13 different groups, so the code takes 13 first colors (which are in the first row in the screenshot below): enter image description here

Then MyDomainColors looks like this: enter image description here

So, my logic is that the first 13 colors should be matched with the elements of MyDomainColors, i.e. NA being "#808080", Group94 being red, etc. And it works until palegreen which should be associated with Group475. But here is what I get:

enter image description here

Group 475 gets #AB82FF which is purple. It looks like it simply skipped palegreen and wheat2. Also, I get the following warning:

enter image description here

I do not understand the warning either. So, what is wrong here?

0

There are 0 best solutions below