YuLab-SMU/tidytree

Using different colours for positive and negative values in `gheatmap`

Closed this issue · 3 comments

Hello,

I need to use a custom colour legend for heatmaps that shows positive and negative values as different colour gradients (e.g. warm colours for positive, blues for negative values). I also need to hide/squeeze the range of values around zero without data.

Here is some data

library(ggtree)
library(treeio)
library(ggplot2)
beast_file <- system.file("examples/MCC_FluA_H3.tree", package="ggtree")
beast_tree <- read.beast(beast_file)

genotype_file <- system.file("examples/Genotype.txt", package="ggtree")
genotype <- read.table(genotype_file, sep="\t", stringsAsFactor=F)
colnames(genotype) <- sub("\\.$", "", colnames(genotype))

p <- ggtree(beast_tree, mrsd="2013-01-01") + 
  geom_tiplab(size=2, align=TRUE, linesize=.5) + 
  theme_tree2()
set.seed(1000)

Vals <- c(rnorm(100000, 0.6, 0.2), rnorm(100000, -0.6, 0.2))
Vals[Vals > 1] <- 1
Vals[Vals < -1] <- -1
Vals <- sample(Vals, 76*8)
Vals[Vals < 0.6 & Vals > -0.8] <- NA

set.seed(1000)
genotype[] <- sample(Vals, 76*8)
genotype1 <- genotype2 <- genotype[]
genotype1[genotype1 < 0] <- genotype2[genotype2 > 0] <- NA

The following plot spans the full range of values from -1 to 1. There are no values between -0.8 and 0.6.

gheatmap(
  p, genotype, offset=8, width=0.6, colnames=FALSE, legend_title="genotype") +
  ggplot2::scale_fill_gradientn(na.value = "transparent", colours = colorRamps::matlab.like(200))

image

Is it possible to make distinct colours for the positive and negative ranges of values? I need to get something like the following on the same plot.

gheatmap(
  p, genotype1, offset=8, width=0.6, colnames=FALSE, legend_title="genotype") +
  ggplot2::scale_fill_gradientn(na.value = "transparent", colours = colorRampPalette(c("lightblue", "darkblue"))(100))
gheatmap(
  p, genotype2, offset=8, width=0.6, colnames=FALSE, legend_title="genotype") +
  ggplot2::scale_fill_gradientn(na.value = "transparent",  colours = rev(colorRampPalette(c("yellow", "red"))(100)))

image image

Is it possible to add two gheatmap functions together and show separate legends on the plot? Something like

genotype1Positve <- genotype1[genotype1 >= 0]
genotype1Negative <- genotype1[genotype1 < 0]
gheatmap(
  p, genotype1Positve, offset=8, width=0.6, colnames=FALSE, legend_title="genotype") +
  gheatmap(genotype1Negative, offset=8, width=0.6, colnames=FALSE, legend_title="genotype") +
  ggplot2::scale_fill_gradientn(na.value = "transparent", colours = colorRamps::matlab.like(200))

Thanks

I am sorry. I just realized that I posted this not in the right repo. Should I repost this issue on the ggtree repo instead?

Yes, it is supported. Please refer to https://yulab-smu.top/treedata-book/chapter7.html#gheatmap.

Thanks @GuangchuangYu. I found out how to solve it.