How to show legend in heatmap?

旧时模样 提交于 2020-06-25 22:20:10

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/57395558/how-to-show-legend-in-heatmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!