Initially I was trying to add the horizontal color side bar to the dendrogram plot (NOT to the whole heat map) using colored_bars from dendextend.
The code below (THANK YOU for your help Tal!) works pretty well. The only issue remaining is how to control the distance of the bar from the leaves labels and the bar width?
Here is an example, data and code
Data (4 variables, 5 cases)
df <- read.table(header=T, text="group class v1 v2
1 A 1 3.98 23.2
2 A 2 5.37 18.5
3 C 1 4.73 22.1
4 B 1 4.17 22.3
5 C 2 4.47 22.4
")
car_type <- factor(df[,c(1)]) # groups codes (A,B,C)
cols_4 <- heat.colors(3)
col_car_type <- cols_4[car_type]
matrix<-data.matrix(df[,c(3,4)])
rnames<-df[,2]
row.names(matrix)<-rnames
matrix<-data.matrix(df[,c(3,4)])
row.names(matrix)<-rnames
dend<-hclust(dist(matrix))
labels_colors(dend) <- col_car_type[order.dendrogram(dend)] # Error in order.dendrogram(dend) : 'order.dendrogram' requires a dendrogram
# But I dont think the line above is doing anything so it can be removed...
plot(dend)
colored_bars(col_car_type, dend)