3
votes

I need help assigning the correct hex color codes to ggplot + geom_tile() for a 86x86 matrix. It is a correlation matrix and I want to color it depending on its value and class generated by kmeans clustering. There are six different clusters/colors. Here is pseudocode:

value[i,j] < 0.7, color '#FBB4AE'
value[i] == value[j] then color it according to its cluster value from kmeans 
else: color '#FED9A6'

Here is a snippet of the data (11x6):

1   1.000000000  0.39444675  0.71206533  0.45434411  0.39223227  0.450000000
2   0.394446746  1.00000000  0.67660082  0.52710164  0.48768778  0.457329560
3   0.712065332  0.67660082  1.00000000  0.66864785  0.52839595  0.641500299
4   0.454344111  0.52710164  0.66864785  1.00000000  0.52414242  0.356348323
5   0.392232270  0.48768778  0.52839595  0.52414242  1.00000000 -0.147087101
6   0.450000000  0.45732956  0.64150030  0.35634832 -0.14708710  1.000000000
7   0.511111111  0.35252487  0.64150030  0.84632727  0.27238352  0.490740741
8   0.064888568  0.26429707 -0.01560976  0.08671100 -0.07953560  0.243332132
9   0.307350428  0.40105559  0.52720311  0.80357143  0.38000325  0.356348323
10  0.509636861  0.25374774  0.44294040  0.19771865 -0.04836194  0.630196118
11  0.394557570  0.21145645  0.07909650  0.52724973  0.22568906 -0.027399831

I have a separate (7396x1) vector named flavors.color that includes the hex color codes that correspond to each element of the 86x86 matrix. These color codes are based on the condition I stated above. The top part is a table of occurrences of each element. #CCCCCC is most frequent.

color

After melting:

p<-ggplot(data=corr.melt,aes(Var1,Var2)) + geom_tile(aes(fill=flavors.color),color="white") 
p+ scale_fill_manual(values = unique(flavors.color))

#CCCCCC is 'grey' however in my plot it colors it purple. I defined my colors from brewer.pal(6,"Set2") and manually added two more colors, #CCCCCC and #FFFFCC. In Set2 purple is in the fourth position. So, the 'grey', 'white' and 'purple' are mixed up and I don't know why. Here is a photo of the result.

plot

1

1 Answers

1
votes

You can do this by creating a 86x86 grid.

 x <- seq(1,86)
 y <- seq(1,86)
 yxs <- expand.grid(x,y)
 yxs$flavors.color <- flavors.color
 ggplot(yxs,aes(x=Var1,y=Var2))+geom_tile(aes(fill=flavors.color))