The problem is actually quite simple, yet I am not able to find a solution to it.
How to plot a heatmap and its legend, i.e. a bar with the color scale representing the minimum and the maximum value that are plotted?
I read the help of the heatmap() function, and using base R as explained here:
r-graph-gallery.com heatmaps
this is what I'm doing
heatmap(as.matrix(dataSet[, -1]), Colv = NA, Rowv = NA, scale="column", xlab="something", ylab="", main="A title", labRow=dataSet$labels, labCol=colnames(dataSet[, -1]), col= colorRampPalette(brewer.pal(8, "Oranges"))(25))
and it works perfectly, but still I would like to plot a legend. Is there a way to do that?
this is a sample of the dataset which I'm working with. The first row is the header.
labels 6 1 4 8 3 2 9 7 5
aaa1 2 2 11 0 0 0 0 0 0
aaa2 3 3 16 0 0 0 0 0 0
aaa3 1 4 15 0 0 0 0 0 0
aaa4 1 6 17 0 0 0 0 0 4
aaa10 1 2 16 0 0 0 0 0 0
bbb11 1 0 2 0 1 2 1 0 0
bbb12 0 1 10 1 0 1 2 3 0
bbb13 1 0 0 0 2 0 0 0 0
The legends for heatmaps are composed with a color bar, labels and titles. ComplexHeatmap automatically generates legends according to the input matrix and annotations, while also provide flexibility to customize and add new legends.
A heatmap (aka heat map) depicts values for a main variable of interest across two axis variables as a grid of colored squares. The axis variables are divided into ranges like a bar chart or histogram, and each cell's color indicates the value of the main variable in the corresponding cell range.
A row of white means "no variation".
How to Read a Heat Map? Reading a heat map depends on which data is represented on that particular map. Bear in mind that warmer colors indicate higher values and colder colors indicate lower values. Red is the warmest color and purple is the coldest in these maps.
You need to add the legend
function as a separate line.
library(RColorBrewer)
dataSet<-read.table(header=TRUE, text="labels 6 1 4 8 3 2 9 7 5
aaa1 2 2 11 0 0 0 0 0 0
aaa2 3 3 16 0 0 0 0 0 0
aaa3 1 4 15 0 0 0 0 0 0
aaa4 1 6 17 0 0 0 0 0 4
aaa10 1 2 16 0 0 0 0 0 0
bbb11 1 0 2 0 1 2 1 0 0
bbb12 0 1 10 1 0 1 2 3 0
bbb13 1 0 0 0 2 0 0 0 0")
heatmap(as.matrix(dataSet[, -1]), Colv = NA, Rowv = NA,
scale="column", xlab="something", ylab="", main="A title",
labRow=dataSet$labels, labCol=colnames(dataSet[, -1]),
col= colorRampPalette(brewer.pal(8, "Oranges"))(25))
legend(x="bottomright", legend=c("min", "ave", "max"),
fill=colorRampPalette(brewer.pal(8, "Oranges"))(3))
Since you are scaling by the column, I am not sure what the expected range should be. In the example above, I assumed 3 levels in the legend. For better placement of the legend, you can adjust the x option or specify a x and y coordinate. See ?legend
for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With