raivokolde / pheatmap

Pretty heatmaps
225 stars 83 forks source link

Convenient coloring function for annotation cols/rows #67

Open atakanekiz opened 4 years ago

atakanekiz commented 4 years ago

Hello,

Thanks for this great package. I have a question/suggestion about assigning annotation colors.

Sometimes the default color scheme makes it difficult to distinguish annotation groups. In this case, I create a list containing named color vectors such as:

annot_colors <- list(annot1=c("grp1"="red, "grp2"="blue"))

If the vectors are unnamed, the algorithm throws an error about the unmatched factor levels. Here is the question: Is there a faster way of dealing with unwanted colors?

If there isn't, I would suggest a function that the users can simply provide the color names without the need for matching the factor levels to specific colors.

I'm sure it can be made more elegant, but I have written a small function to help this:

colormatcher <- function(colannot, # column annotation data frame
                      rowannot, # row annotatoin data frame
                      var_to_color # list of vectors matching vars to colors
                      ){

    annot_list <- c(as.list(colannot), as.list(rowannot))

    annot_list <- lapply(annot_list, levels)

    for(i in names(var_to_color)){

        names(var_to_color[[i]]) <- annot_list[[i]]

    }

    var_to_color

}

#### TEST

rowannot <- data.frame(species = iris$Species)
colannot <- data.frame(part=factor(c("sepal", "sepal", "petal", "petal")))

rownames(iris) <- seq_along(1:dim(iris)[1])

rownames(rowannot) <- rownames(iris)
rownames(colannot) <- colnames(iris[, -5])

annot_colors <- colormatcher(colannot,
                             rowannot,
                             var_to_color = list(species=c("red", "black", "gold2"),
                                                 part=c("orange", "gray")))

pheatmap(iris[, -5], 
         annotation_row = rowannot,
         annotation_col = colannot,
         annotation_colors = annot_colors)
atakanekiz commented 1 year ago

An edit years later to make things easier with non-factor variables:

colormatcher <- function(colannot, # column annotation data frame
                      rowannot, # row annotatoin data frame
                      var_to_color # list of vectors matching vars to colors
                      ){

    annot_list <- c(as.list(colannot), as.list(rowannot))

    annot_list <- lapply(annot_list, function(x) levels(as.factor(x))

    for(i in names(var_to_color)){

        names(var_to_color[[i]]) <- annot_list[[i]]

    }

    var_to_color

}